I am currently exploring Angular and trying to grasp the concept of connecting different controllers to update their values based on changes in one controller.
In a specific scenario, I have a form with ngModel and I am attempting to utilize ngModelChange to automatically update another property in my model. The challenge arises when ngModelChange is triggered only by user interaction with the control, not when the model is updated from the component.
For reference, here is an example code snippet:
https://stackblitz.com/edit/angular-ivy-z2q4mr
HTML Template:
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<mat-form-field appearance="fill">
<mat-label>Field 1</mat-label>
<input matInput name="field1" [(ngModel)]="MyItem.field1" (ngModelChange)="changeField2($event)">
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Field 2</mat-label>
<input matInput disabled name="field2" [(ngModel)]="MyItem.field2" (ngModelChange)="changeField3($event)">
</mat-form-field>
<mat-form-field appearance="fill"</gt;
<mat-label>Field 3</mat-label>
<input matInput disabled name="field3" [(ngModel)]="MyItem.field3">
</mat-form-field>
</form>
Component
import { OnInit, Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {
MyItem : any = {}
constructor() {
}
ngOnInit(): void {
}
changeField2(event: any){
this.MyItem.field2 = this.MyItem.field1 + " modification field 2";
}
changeField3(event: any) {
this.MyItem.field3 = this.MyItem.field2 + " modification field 3";
}
}
The desired outcome is for field3 to be updated automatically when making changes to field1, as it is indirectly related through field2. While calling changeField3
inside changeField2
is a possible solution, managing multiple controllers can make this approach cumbersome due to potential repetitive calls.