@ViewChild と @ContentChild の違いは何ですか? 質問する

@ViewChild と @ContentChild の違いは何ですか? 質問する

Angular 2 は@ViewChild、コンポーネントの子孫要素を照会するための、、およびデコレータを@ViewChildren提供@ContentChildします。@ContentChildren

最初の 2 つと最後の 2 つの違いは何ですか?

ベストアンサー1

Shadow DOMLight DOMの用語を使ってあなたの質問に答えます(これはWebコンポーネントから来ています。ここ)。 一般的に:

  • Shadow DOMは、コンポーネントの作成者によって定義され、エンドユーザーからは隠されるコンポーネントの内部 DOM です
@Component({
  selector: 'some-component',
  template: `
    <h1>I am Shadow DOM!</h1>
    <h2>Nice to meet you :)</h2>
    <ng-content></ng-content>
  `;
})
class SomeComponent { /* ... */ }
  • Light DOM -コンポーネントのエンドユーザーがコンポーネントに提供するDOM です。例:
@Component({
  selector: 'another-component',
  directives: [SomeComponent],
  template: `
    <some-component>
      <h1>Hi! I am Light DOM!</h1>
      <h2>So happy to see you!</h2>
    </some-component>
  `
})
class AnotherComponent { /* ... */ }

したがって、あなたの質問に対する答えは非常に簡単です:

と の違いは@ViewChildren、は Shadow DOM で要素を検索するのに対し、 はLight DOM で要素を検索する@ContentChildren点です。@ViewChildren@ContentChildren

おすすめ記事