When I click on the reset button in Parent UI, I want to reset the child's property. This works for the first time. i.e, Child's ngOnChanges method is not called the second time when I click on Parent's reset button.
The below option works fine for me. i.e, defining a two-way binding in child and pass the state back to parent via this.resetChange.emit(false); So what's happening is when parent's resetTriggered is set to false, child's ngOnChanges is called immediately and since there is no else condition (if(this.resetTriggered)), it stops there in child.
Is there a better solution? i.e, I don't want to pass the variable state to parent and parent to handle this event. Child should handle everything so that there is no dependency on parent to handle this child's state change.
Parent HTML:
<app-customer (select)="onCustomerIdSelect($event)" [(reset)]="resetTriggered"></app-customer>
<div style="text-align: right;padding-right: 10px;padding-top: 110px;">
<button class="btn btn-primary submit" (click)="resetFilters()">Reset</button>
</div>
Parent Component:
resetTriggered: boolean = false;
onLocationReset(resetChild: boolean){
this.resetTriggered = resetChild;
}
ngAfterViewInit(){
this._changeDetectorRef.detectChanges();
}
ngAfterViewChecked(){
this._changeDetectorRef.detectChanges();
}
resetFilters() {
console.log('resetFilters()');
this.resetTriggered = true;
this.searchRequest.reset();
}
Child Component:
resetTriggered: boolean;
@Output() resetChange: EventEmitter<boolean> = new EventEmitter<boolean>();
@Input() set reset(value) {
this.resetTriggered = value;
}
ngOnChanges()
{
console.log('reset in child - ' + this.resetTriggered);
if(this.resetTriggered)
{
this.resetChange.emit(false);
this.resetData();
}
}