2017-02-20 6 views
1

У меня есть компонент с:Угловое 2 находка QueryList в

@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: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'property' of undefined

UPDATE:

Проблема я думаю, что существует из-за динамического формообразования. Here - плукер. В app.ts У меня есть код, указанный выше.

ответ

3

Он работает как шарм:

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 продемонстрировать?

Или добавить дополнительные проверки, если действительно была найдена директива ?!

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

Я обновил этот вопрос, спасибо –

+0

Вы только пропустили 0,5%! ;) Взгляните на мой измененный ответ. – mxii

+0

Хорошо, мне удастся как-то иначе, с setTimeout не очень хорошая практика –

 Смежные вопросы

  • Нет связанных вопросов^_^