Home > database >  How to use patchValues() with the <mat-form-field > on the (keyup.enter) event binding
How to use patchValues() with the <mat-form-field > on the (keyup.enter) event binding

Time:10-13

I am trying to populate the city based on zip code field. I am able to do the aforementioned using normal html tag with the (keyup) event binding, but with css I have to use (keyup.enter) which is able to invoke the function which is bind with event call but it is not letting the patchValue() function work properly. Here's a snippet of my code :-

editor.component.ts

profileForm = this.fb.group({
    name: ['', Validators.required],
    address: this.fb.group({
             zip: ['', Validators.required],
             city: ['', Validators.required]})
             });


func(event: any){
  this.profileForm.patchValue({
      address:{
      city: this.getCity(event.value)
      }
    })  
}

getCity = (theCurrentZip: any) => {
  return Object.keys(this. zipCode).filter(z => {
    return this.zipCode[z].includes(theCurrentZip)
  })[0]
}

zipCode: any = {
  "A": ["1", "2" ],
  "B":[ "3", "4",]
};

editor.component.html

<div>
<form (ngSubmit)="onSubmit()" #myForm="ngForm" class="profileForm">
<mat-form-field required>
  <input matInput id="name" placeholder="Contact Name" name="name" [(ngModel)]="name">
</mat-form-field >
<div formGroupName="address">
<mat-form-field >
    <input matInput id="zip" (keyup)="func($event.target)" placeholder="Zip" name="zip" [(ngModel)]="zip" >
  </mat-form-field >
  <mat-form-field required>
    <input matInput id="city" placeholder="City" name="city" [(ngModel)]="city" >
  </mat-form-field >
</div>
<p>
    <button type="submit" mat-raised-button color = "primary">Submit</button>
</p>
</form>
</div>

CodePudding user response:

As far as I can see you're currently mixing the reactive and template-driven approach of Angular forms.

The reactive approach is used in your editor.component.ts and the template-driven one in your editor.component.html.

Since your HTML is template-driven it is not necessary to call patchValue because the form and the form controls are not bound to the HTML. So, to update your HTML you need to adjust your implementation of func like following

func(event) {
  this.city = this.getCity(event.target.value);
}

My suggestion for you would be that you choose one of those approaches and don't mix them (if it isn't absolutely necessary). Also, you should use more meaningful function names than func ;)

  • Related