简体   繁体   English

Angular 2 QueryList的查找

[英]Angular 2 QueryList's find

I have a component with: 我有一个组件:

@ViewChildren(MyDirective) factories: QueryList<MyDirective>;

when I want to find an element in the QueryList it is working: 当我想在QueryList找到一个元素时它正在工作:

ngAfterViewInit() {
    let field1 = this.factories.find(factory => factory.meta.id == 'field1');
    console.log(field1);    
}

MyDirective {vcRef: ViewContainerRef_, loader: MyLoaderService, meta: Object} MyDirective {vcRef:ViewContainerRef_,loader:MyLoaderService,meta:Object}

But when I try to access a property of field1 : 但是当我尝试访问field1的属性时:

ngAfterViewInit() {
    let field1 = this.factories.find(factory => factory.meta.id == 'field1');
    console.log(field1.property);    
}

EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'property' of undefined EXCEPTION:未捕获(在承诺中):错误:错误:0:0引起:无法读取未定义的属性'property'

UPDATE: 更新:

The problem I think exists because of dynamic form creation. 我认为存在的问题是因为动态表单创建。 Here is a plunker. 是一个掠夺者。 In app.ts I have the code above. app.ts我有上面的代码。

It works like a charm: 它就像一个魅力:

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);
  }
}

my working demo: https://plnkr.co/edit/gCxYCnCd6Wdm0de4REXp?p=preview 我的工作演示: https//plnkr.co/edit/gCxYCnCd6Wdm0de4REXp?p = preview

Maybe you could create a plunker to demonstrate? 也许你可以创建一个plunser来演示?

Or add some additional checks if really a directive was found?! 或者如果确实找到了指令,还要添加一些额外的检查?!

UPDATE UPDATE

Here is your modified plunker: https://plnkr.co/edit/CRjONEtMAe085btR5oGi?p=preview 这是你修改过的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM