Rajasekhar
Rajasekhar

Reputation: 2455

Toggle textboxes using angular

Have to show one textbox only at a time, if click on toggle need to hide first textbox and need to show second textbox. If I click again need to show first textbox and hide second textbox. Tried below, but unable to display one textbox onload itself...

HTML:

 <div><input *ngIf="text1"
  id="test1"
  type="text"
  placeholder="Textbox1"
/>
</div>
<div>
<input *ngIf="text2"
  id="test2"
  type="text"
  placeholder="Textbox2"
/>
</div>

<button (click)="toggle()">Toggle</button>

.ts

 toggle() {
    this.text1 = !this.text1;
    if (this.text1) {
      this.text2 = false;
      this.text1 = true;
    } else {
      this.text2 = true;
      this.text1 = false;
    }
  }

Demo

Upvotes: 0

Views: 462

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

Tried below, but unable to display one textbox onload itself

you can set the boolean of one of the text boxes to true:

public text1: boolean = true;

Using a single variable to track the visibility:

export class NgbdTypeaheadTemplate {
  public showText1: boolean = true;

  toggle() {
    this.showText1 = !this.showText1;
  }
}

and

<div><input *ngIf="showText1"
  id="test1"
  type="text"
  placeholder="Textbox1"
/>
</div>
<div>
  <input *ngIf="!showText1"
  id="test2"
  type="text"
  placeholder="Textbox2"
/>
</div>

Upvotes: 1

Owen Kelvin
Owen Kelvin

Reputation: 15083

You can use 1booleanItem

toggle() {
    this.text1 = !this.text1;
}
<div><input *ngIf="text1"
  id="test1"
  type="text"
  placeholder="Textbox1"
/>
</div>
<div>
  <input *ngIf="!text1"
  id="test2"
  type="text"
  placeholder="Textbox2"
/>
</div>

<button (click)="toggle()">Toggle</button>

Demo

Upvotes: 2

Related Questions