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?
Since you are using reactive forms with the
formControlName
directive, you do not need to usengModel
at all, so you can remove that from themat-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:So then
form.controls['pro_cate_id'].value
would give you the value of themat-select
control, and you can use it like this:Also, you could disable the button rather than remove it entirely if you want: