angular2,读取的内容:ViewChild中使用的属性?

时间:2016-06-15 15:52:13

标签: angular

我理解并经常使用@ViewChild,但{read}道具用于什么?

如:@ ViewChild('putStuffHere',{read:ViewContainerRef})putStuffHere;

请参阅以下代码:

import {Component, ViewChild, ViewContainerRef, ComponentResolver} from '@angular/core';

@Component({
  selector: 'my-component',
  template `<h1>my-component</h1>`
})
class MyComponent{}

@Component({
  selector: 'my-app',
  template: `
    <h2>Above</h2>
    <div #putStuffHere></div>
    <h2>Below</h2>
  `
})
export class AppComponent {
  @ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere;

  constructor(
      public view:ViewContainerRef,
      public compResolver:ComponentResolver
  ){}

  ngAfterViewInit(){
    this.compResolver.resolveComponent(MyComponent)
      .then(factory => {
        this.putStuffHere.createComponent(factory);    
      })

  }
}

问候

肖恩

1 个答案:

答案 0 :(得分:1)

它允许访问ViewContainerRef个实例,而不是ElementRef个实例。

以下是一个示例:

@ViewChild('putStuffHere') putStuffHere1:ElementRef;
@ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere2:ElementRef;