Button click to render textarea giving error

64 Views Asked by At

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; 
}
2

There are 2 best solutions below

0
Hezy Ziv On BEST ANSWER

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>
0
Ahmed El-sayed On

If you imported it correctly try to make two versions from mat-form-field one with textarea and the second without it to avoid changing the style and get rid of the error.

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