Let's begin by addressing the implementation issue before delving into potential solutions.
The Issue at Hand
The problem arises when altering the value in the first textbox triggers the ngOnChange() lifecycle hook, calculates the square value, and updates the second textbox. However, updating the value in the second textbox subsequently triggers ngOnChange() again, prompting further changes and updates in an endless loop.
A Possible Solution
Constructing the Component Design Structure
child.component.html
<input type="text" name="name1" id="txtName2" [(ngModel)]="childText" (change)="valuechange2($event.target.value)" />
child.component.ts
import { Component, Input, OnChanges, SimpleChange, SimpleChanges, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnChanges {
@Input() childText: number;
@Output() text2Change: EventEmitter<number> = new EventEmitter<number>();
constructor() { }
ngOnChanges(changes: SimpleChanges) {
let currentVal = changes.childText.currentValue;
let previousVal = changes.childText.previousValue;
if (currentVal != previousVal) {
this.childText = currentVal * currentVal;
}
}
valuechange2(val: number) {
this.text2Change.emit(val);
}
}
Child2.component.html
<input type="text" name="name1" id="txtName3" [(ngModel)]="childText" (change)="valuechange2($event.target.value)" />
Child2.component.ts
import { Component, Input, OnChanges, SimpleChange, SimpleChanges, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child1-component',
templateUrl: './child1.component.html'
})
export class Child1Component implements OnChanges {
@Input() childText: number;
@Output() text2Change: EventEmitter<number> = new EventEmitter<number>();
constructor() { }
ngOnChanges(changes: SimpleChanges) {
let currentVal = changes.childText.currentValue;
let previousVal = changes.childText.previousValue;
if (currentVal != previousVal) {
this.childText = currentVal * currentVal;
}
}
valuechange2(val: number) {
this.text2Change.emit(val);
}
}
Parent Component
app.component.html
<child-component [childText]="text1" (text2Change)="childChange($event)"></child-component>
<child1-component [childText]="text2" (text2Change)="child1Change($event)"></child1-component>
app.component.ts
import { Component, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { of, merge } from 'rxjs';
import { mergeMap, delay } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnChanges, OnInit, OnChanges {
title = 'my-app';
text1: number;
text2: number;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
childChange(child: number) {
this.text2 = child;
}
child1Change(child: number) {
this.text1 = child;
}
}