简体   繁体   中英

How to notify parent about change in child component?

I have a child component with this template:

<p *ngIf="user != null" >
    Id: {{user.id}}<br>
    Name: {{user.firstName}} {{user.lastName}}<br>
    Nick: {{user.nickname}}<br>
    Gender: {{user.gender}}<br>
    Birthday: {{user.birthday}}<br>
    Last login: {{user.lastUpdateDate}}<br>
    Registered: {{user.registrationDate}}<br>
</p>

I get user from server using http request, so when data is loaded, user is shown.

How can I notify parent component that data was loaded and shown?

Simply by using EventEmitter in child component (this example works with click event, you can emit the event whenever you want to).

@Component({
  selector: 'child-component',
  template: `
    <button (click)="changeState(State.FINISHED)">Finish</button>
  `
})
export class ChildComponent {
  @Output() stateChanged = new EventEmitter<State>();

  changeState(state: State) {
    this.stateChanged.emit(state);
    ...
  }
}

@Component({
  selector: 'parent-component',
  template: `
    <child-component
      (stateChanged)="onStateChange($event)">
    </child-component>
  `
})
export class ParentComponent {
  onStateChange(state: State) {
    ...
  }
}

When you click on the Finish button, it calls the changeState method, where the stateChange event is emited. It can be listened to as seen in parent component's template. This will call the onStateChange method where you react to the event however you want to.

See Component Interaction article in Angular.io docs for more info

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