[英]How to make a component listen and wait for data from another component without an event in Angular 5?
我在使用兩個組件(彈出窗口)時遇到問題,其中我必須將數據從chlid組件發送到另一個沒有事件提取該數據的組件(父母)。 從邏輯上講,我必須找到一種功能,使父母能夠聽取孩子所做的更改。 更改必須在兩個組件中同時出現。 有人可以幫忙嗎?
是的,您可以使用共享的BehaviorSubject來推送值,並且兩個組件都必須訂閱才能獲得此更改
答案就在您的問題上。 您需要一個Output屬性,它是JS事件的Angular概括。
在您的子組件中:
class ChildComponent {
@Input() someProperty: string;
@Output() dataChanged = new EventEmitter<string>();
whenSomethingHappensInChild() {
this.dataChanged.emit('something');
}
}
在您的父模板中:
...
<app-child [someProperty]="'someValue'" (dataChanged)="doSomething($event)"></app-child>
...
在您的父代碼中:
class ParentComponent {
...
doSomething(theValue: string) {
// TA-DAA! you have the value.
}
...
}
請幫個忙,閱讀DOCS,或者更好的是一本書;)
特別是: https : //angular.io/guide/architecture-components完整介紹了綁定的基本知識,而這個問題屬於其中。
祝你今天愉快。
解決的問題:我使用@Host()標記獲取Parent組件的當前實例,並訪問更改其屬性的方法。
這是您應該做的。
第一:您應該在子對象中確定父元素
parent:ParentComponent;
第二:您應該將當前的父實例傳遞給構造函數中的新聲明
constructor(@Host() currentParent:ParentComponent){
this.parent=currentParent
}
第三:現在嘗試僅訪問父組件中的方法和屬性
changeParentAttribute(){
this.parent.iAmInTheParent();
}
我希望這個對你有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.