How can avoid the use of ngModel

963 Views Asked by At

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

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?

2

There are 2 best solutions below

1
Mike Jerred On BEST ANSWER

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">
  ...
  <mat-form-field>
    ...
  </mat-form-field>
</element>

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>
1
Harel Malichi On

usually when using angular reactive forms you already have the binding of the control with the data when you write on each field the formControlName="xxxx" so you already have an access to the field value. If you still want to use the [(ngModel)] with the <mat-select> you can wrap it around with another *ngIf="filterCate" so the [(ngModel)] won't render until this property exists.