简体   繁体   中英

Angular Parent Child communication

When I click on the reset button in Parent UI, I want to reset the child's property. This works for the first time. ie, 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. ie, 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? ie, 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();
    }
  }

I would highly recommend to have component interaction out of direct binding via @Input/@Output between parent and child. For many minor structures this might work, but as soon as you have large projects with multi-level nesting, you might run into headache when trying to bleed through your variables from top to bottom.

A better solution would be to have communication over a bus, that allows emission/dispatching and receiving/subscription to data. A good start would be ngrx => Angular redux implementation ( https://github.com/ngrx ). There you can achieve data-flow unbound to component hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM