Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
andrew554 Avatar asked Nov 09 '16 21:11

andrew554


People also ask

How do you update the state of parent component from the child component?

To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.


1 Answers

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

like image 101
jirig Avatar answered Sep 28 '22 04:09

jirig