[英]Angular2: child component access parent class variable/function
我在父組件中有一個可能由child更改的變量,parent將在視圖中使用此變量,因此必須傳播更改。
import {Component, View} from 'angular2/core';
@Component({selector: 'parent'})
@View({
directives: [Child],
template: `<childcomp></childcomp>`
})
class Parent {
public sharedList = new Array();
constructor() {
}
}
@Component({selector: 'child'})
@View({template: `...`})
class Child {
constructor() {
//access 'sharedList' from parent and set values
sharedList.push("1");
sharedList.push("2");
sharedList.push("3");
sharedList.push("4");
}
}
如果您使用帶有JavaScript引用類型的輸入屬性數據綁定(例如,Object,Array,Date等),那么父級和子級都將引用相同/一個對象。 您對共享對象所做的任何更改都將對父級和子級都可見。
在父模板中:
<child [aList]="sharedList"></child>
在孩子:
@Input() aList;
...
updateList() {
this.aList.push('child');
}
如果要在構造子項時將項添加到列表中,請使用ngOnInit()
掛鈎(而不是構造函數(),因為此時未初始化數據綁定屬性):
ngOnInit() {
this.aList.push('child1')
}
這個Plunker顯示了一個工作示例 ,父組件和子組件中的按鈕都修改了共享列表。
請注意,在孩子中,您不得重新分配參考。 例如,不要在子this.aList = someNewArray;
執行此操作: this.aList = someNewArray;
如果這樣做,那么父組件和子組件將分別引用兩個不同的數組。
如果你想共享一個基本類型(即字符串,數字,布爾值),你可以將它放入一個數組或一個對象(即,將它放在一個引用類型中),或者你可以emit()
一個來自孩子的事件每當原始值發生變化時(即讓父級監聽自定義事件,子級將具有EventEmitter
輸出屬性。有關詳細信息,請參閱@ kit的答案。)
更新 2015/12/22: 結構指令指南中的heavy-loader
示例使用了我上面介紹的技術。 主/父組件具有綁定到子組件的logs
數組屬性。 子組件push()
到該數組上,父組件顯示該數組。
NgModel和NgForm有什么關系呢? 您必須將父級注冊為提供者,然后將父級加載到子級的構造函數中。
這樣,您就不[sharedList]
放在所有孩子[sharedList]
。
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
那你的HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
您可以在Angular文檔中找到有關該主題的更多信息: https : //angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection
您可以在父組件聲明中執行此操作:
get self(): ParenComponentClass {
return this;
}
在子組件中,在包含ParenComponentClass的導入之后,聲明:
private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
this._parent = value;
}
get parent(): ParenComponentClass {
return this._parent;
}
然后在父母的模板中你可以做
<childselector [parent]="self"></childselector>
現在,從孩子可以訪問父母使用的公共屬性和方法
this.parent
基本上,您無法直接從父級訪問變量。 你通過事件來做到這一點。 Component的輸出屬性負責這一點。 我建議閱讀https://angular.io/docs/ts/latest/guide/template-syntax.html#input-and-output-properties
關於此主題的Angular2文檔中的主要文章是:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child
它包括以下內容:
使用輸入綁定將數據從父級傳遞給子級
使用setter攔截輸入屬性更改
攔截輸入屬性隨ngOnChanges而變化
家長偵聽子事件
父通過局部變量與子進行交互
Parent調用ViewChild
家長和孩子通過服務進行交流
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.