How can avoid the use of ngModel


I’ve been stuck on something for hours and I need some help. I’m pretty new to angular.
I’m working with the reactive forms, showing my code and explaining what I want to accomplish.

  <mat-select [(ngModel)]="filterCate"
    placeholder="Cate" type="search" aria-label="Search" 
    name="search" (focus)="getControl($event)">
    <mat-option *ngFor="let cate of categorias" [value]="">{{}}</mat-option>
  <button mat-button *ngIf="filterCate" matSuffix mat-icon-button aria-label="Clear"
    (click)="$event.stopPropagation(); deleteField('pro_cate_id')">

I have a ng-if where a button is shown to reset the field, and I only need it to be shown when there is a value in the field. I get the error "Property ‘filterCate’ does not exist on type ‘xxxComponent’"
I know that with the two-way I need that value to exist in the component, if I create the variable there is no problem. But I have about 20 more fields and I don’t seem to create 20 variables for all the fields. What could I do in this case, how could I refactor this code without the ng-model in all of the mat-form-field?


Since you are using reactive forms with the formControlName directive, you do not need to use ngModel at all, so you can remove that from the mat-select.

Now to get the value of your form control pro_cate_id, you need to reference its form group. Presumably in your html you have something like:

<element [formGroup]="form">

So then form.controls['pro_cate_id'].value would give you the value of the mat-select control, and you can use it like this:

<button *ngIf="form.controls['pro_cate_id'].value"></button>

Also, you could disable the button rather than remove it entirely if you want:

<button [disabled]="!form.controls['pro_cate_id'].value"></button>

Answered By – Mike Jerred

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.