[英]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.我使用 http 请求从服务器获取用户,因此在加载数据时,会显示用户。
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).只需在子组件中使用
EventEmitter
(此示例适用于单击事件,您可以随时发出该事件)。
@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.当您单击
Finish
按钮时,它会调用changeState
方法,在该方法中发出stateChange
事件。 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.这将调用
onStateChange
方法,您可以在其中根据需要对事件做出反应。
See Component Interaction article in Angular.io docs for more info有关更多信息,请参阅Angular.io 文档中的组件交互文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.