【问题标题】:Angular 2 QueryList's findAngular 2 QueryList 的查找
【发布时间】:2017-02-21 20:21:42
【问题描述】:

我有一个组件:

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

异常:未捕获(承诺中):错误:错误:0:0 导致:无法读取未定义的属性“属性”

更新:

我认为存在动态表单创建的问题。 Here 是个笨蛋。在app.ts 我有上面的代码。

【问题讨论】:

    标签: javascript angular promise


    【解决方案1】:

    它就像一个魅力:

    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

    也许你可以创建一个 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);
    }
    

    【讨论】:

    • 好的,我会以其他方式管理,setTimeout 不是一个好习惯
    • 肯定不会! :) 只是想证明问题本身.. :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2018-04-26
    • 2018-07-04
    • 2019-03-25
    • 2019-09-08
    • 2020-08-16
    相关资源
    最近更新 更多