2016-04-27 7 views
3

この動作は、beta16でのみ発生します。以前のリリースは期待どおり動作しています。TemplateRefを検索すると@Queryの動作が異なります

@Queryは子孫要素のテンプレート要素も見つけます。コンテンツ内のTemplate要素を探すコンポーネントを考えます。

export class Container { 

    constructor(@Query(TemplateRef) templates: QueryList<TemplateRef>) { 
     templates.changes.subscribe(_ => { 
      console.log(templates.length); 
     }); 
    } 

} 

@Component({ 
selector: 'my-app', 
template: `<container> 
      <template></template> 
      <child> 
       <template></template> 
      </child> 
      </container>`, 
directives: [Container,Child] 

http://plnkr.co/edit/sANW6mfss5EvPfWpXRde

私は "1" がコンソールにログインすることを期待しますが、 "2" が記録されます。子のテンプレートも見つかります。

しかし、テンプレート要素をいくつかのランダム成分、例えば、 otherchildは、期待される結果を生成します。

export class Container { 

    constructor(@Query(OtherChild) templates: QueryList<OtherChild>) { 
     templates.changes.subscribe(_ => { 
      console.log(templates.length); 
     }); 
    } 

} 


@Component({ 
selector: 'my-app', 
template: `<container> 
      <otherchild></otherchild> 
      <child> 
       <otherchild></otherchild> 
      </child> 
      </container>`, 
directives: [Container,Child,OtherChild] 

})

http://plnkr.co/edit/OzXjz8niAurzr6CZIoes

コンテナは一つだけotherchildを有しているように、 "1" が印刷されています。

混乱の原因となるテンプレート要素とは異なるものがあります。私はこれがバグか意図された動作かどうか疑問に思います。

答えて

1

@Query()@ContentChildren()を好んで使用しています。

ヒント:が呼び出された後にのみ、@ContentChildren()の結果はコンストラクタでアクセスできません。だけでなく、直接の子が、すべての子孫を取得するために渡される

またdescendants: trueニーズ(これは@Query()を変更したものであるかもしれない - このパラメータはそこにも利用できるようになりました場合、私は知らない)

export class Container { 
    @ContentChildren(OtherChild, {descendants: true}) templates; 
    ngAfterContentInit() { 
    console.log(this.templates.length); 
    this.templates.changes.subscribe(_ => { 
     console.log(templates.length); 
    }); 
    } 
} 

Plunker example

私も@ContentChildren()で問題を再現できます。このコードではも印刷されますが、と表示されます。私はこれがベータ版で@ContentChilren()@ViewChildren()への変更によって引き起こされたバグだと考えています。

export class Container { 
    @ContentChildren(TemplateRef, {descendants: false}) templates; 

    ngAfterContentInit() { 
    console.log(this.templates.length); 
    this.templates.changes.subscribe(_ => { 
     console.log(templates.length); 
    }); 
    } 
} 

Plunker example

+1

ありがとうございます。はい、ベータ版では発生しません15テンプレート要素を探すときにのみ適用され、第2のplunkrのotherchildのような他のコンポーネントは期待通りに動作します。私はすでにこの問題を提出しています。 https://github.com/angular/angular/issues/8292 –

関連する問題