[英]Angular 2 QueryList's find
我有一個組件:
@ViewChildren(MyDirective) factories: QueryList<MyDirective>;
當我想在QueryList
找到一個元素時它正在工作:
ngAfterViewInit() {
let field1 = this.factories.find(factory => factory.meta.id == 'field1');
console.log(field1);
}
MyDirective {vcRef:ViewContainerRef_,loader:MyLoaderService,meta:Object}
但是當我嘗試訪問field1
的屬性時:
ngAfterViewInit() {
let field1 = this.factories.find(factory => factory.meta.id == 'field1');
console.log(field1.property);
}
EXCEPTION:未捕獲(在承諾中):錯誤:錯誤:0:0引起:無法讀取未定義的屬性'property'
更新:
我認為存在的問題是因為動態表單創建。 這是一個掠奪者。 在app.ts
我有上面的代碼。
它就像一個魅力:
var __id = 0;
@Directive({ selector: '[mydirective]' })
export class MyDirective {
public uId = ++__id;
}
@Component({
selector: 'my-app',
template: `
<div>
<h2 mydirective>Hello {{name}}</h2>
<h2 mydirective>Hello {{name}}</h2>
<h2 mydirective>Hello {{name}}</h2>
<h2 mydirective>Hello {{name}}</h2>
<h2 mydirective>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
@ViewChildren(MyDirective) factories: QueryList<MyDirective>;
constructor() { this.name = 'Angular2' }
ngAfterViewInit() {
console.log(this.factories);
let field1 = this.factories.find(f => f && f.uId == 1);
console.log(field1);
if (!field1) return;
console.log(field1.uId);
}
}
我的工作演示: https : //plnkr.co/edit/gCxYCnCd6Wdm0de4REXp?p = preview
也許你可以創建一個plunser來演示?
或者如果確實找到了指令,還要添加一些額外的檢查?!
UPDATE
這是你修改過的plunker: https ://plnkr.co/edit/CRjONEtMAe085btR5oGi ? p = preview
ngAfterViewInit() {
let checkbox = this.factories.find(f => f.model.type == 'checkbox'); // use .model
console.log(checkbox.model.data); // use .model
// seems like we need some time here to dynamicly create components ..
console.log('without delay', this.factories.filter(f => !f.componentRef).length);
setTimeout(() => console.log('with delay', this.factories.filter(f => !f.componentRef).length), 100);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.