Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set two way binding without using ngModel in Angular Material

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>
like image 747
radeveloper Avatar asked Sep 17 '25 16:09

radeveloper


2 Answers

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"/>
like image 103
SlimenTN Avatar answered Sep 20 '25 06:09

SlimenTN


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;
  }
like image 26
hjbello Avatar answered Sep 20 '25 07:09

hjbello