Search code examples
angularbuttoninputangular-materialangular-ng-if

Button click to render textarea giving error


I have a button which when clicked , should render a textarea. I am using Angular Material. Tried using ngIf in the textarea tag but giving errors -

Error: mat-form-field must contain a MatFormFieldControl. I have added the library , so I think its the ngIf that is causing the issue.Wrapping textarea tag inside ngcontainer tag and using ngIf in it, gives this error as well. HTML

        <button  mat-raised-button color="primary" (ngSubmit)= "toggleTextBox()">
            Add 
        </button>  
        <form [formGroup]= "limitationForm">  
          <mat-form-field > 
            <mat-label>Textarea</mat-label>            
            <textarea matInput *ngIf= "showTextBox" formControlName="limitTextarea"  
             type="text"  id="limitTextarea" name="limitTextarea" ></textarea>                   
        </mat-form-field>   
       </form>

Ts

toggleTextBox() {
    this.showTextBox = !this.showTextBox; 
}

Solution

  • One solution is to use *ngIf on the <mat-form-field> itself, instead of on the <textarea>:

    <button mat-raised-button color="primary" (click)="toggleTextBox()">Add</button>
    
    <form [formGroup]="limitationForm">
      <ng-container *ngIf="showTextBox">
        <mat-form-field>
          <mat-label>Textarea</mat-label>
          <textarea matInput formControlName="limitTextarea" type="text" id="limitTextarea" name="limitTextarea"></textarea>
        </mat-form-field>
      </ng-container>
    </form>