Issue
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?
Solution
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