[英]How to notify parent about change in child component?
我有一個帶有此模板的子組件:
<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>
我使用 http 請求從服務器獲取用戶,因此在加載數據時,會顯示用戶。
如何通知父組件數據已加載並顯示?
只需在子組件中使用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) {
...
}
}
當您單擊Finish
按鈕時,它會調用changeState
方法,在該方法中發出stateChange
事件。 可以在父組件的模板中看到它。 這將調用onStateChange
方法,您可以在其中根據需要對事件做出反應。
有關更多信息,請參閱Angular.io 文檔中的組件交互文章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.