andrew554 andrew554 - 27 days ago 13
TypeScript Question

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?

Answer

You archieve it using EventEmitter in child component (this example works with click event, you can emitt the event whenever you want to).

@Component({
  selector: 'child-component',
  template: `
    <button (click)="finish(true)">Finish</button>
  `
})
export class ChildComponent {
  @Output() onFinished = new EventEmitter<boolean>();
  finished = false;

  finish(finished: bool) {
    this.onFinished.emit(finished);
    this.finished = finished;
  }
}

When you finish loading your http request, you just call the finished method and catch it in parent component

@Component({
  selector: 'parent-component',
  template: `
    <p *ngIf="showChildRequestFinishedMessage">Finished!</p>
    <child-component
      (onFinished)="onFinished($event)">
    </child-component>
  `
})
export class ParentComponent {
  showChildRequestFinishedMessage = false;
  onFinished(finished: boolean) {
    this.showChildRequestFinishedMessage = finished;
  }
}

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