I am trying to bind a form item to an object without using ngModel. But it is not working.
I tried using the [(value)]="" attribute. However, the initial value of the element changed to "undefined".
https://material.angular.io/components/input/overview
<mat-form-field class="col-md-4">
<input matInput placeholder="First name" formControlName="firstCtrl" [(value)]="formData.firstName">
<mat-error>First name can not be left blank</mat-error>
</mat-form-field>
formData = new RawFormData;
But this one is working correctly:
<mat-form-field>
<mat-select placeholder="Title" formControlName="titleCtrl" [(value)]="formData.gender">
<mat-option *ngFor="let title of personalTitle" [value]="title.value">{{title.viewValue}}</mat-option>
</mat-select>
</mat-form-field>
value
of the input is predefined html attribute and does not emit changes.
In the other hand mat-select
is a custom angular component where they declared value
as input and output at the same time, something like this:
@Input('value') input: any;
@Output('value') output: EventEmitter;
That's why you can bind it in both ways.
so in your case either you work with ngModel
or do something like this:
<input (change)="inputValue = $event.target.value" [value]="inputValue"/>
The only way that comes to my mind of doing it without [ngModel]
is to use (keyup)
. I would try to change your input to something like this:
<mat-form-field class="col-md-4">
<input matInput placeholder="First name" formControlName="firstCtrl" (keyup)="onKey($event)">
<mat-error>First name can not be left blank</mat-error>
</mat-form-field>
and then add a function
onKey(event: any) { // without type info
formData.gender = event.target.value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With