【问题标题】:angular2, what is read: property used for in ViewChild? [duplicate]angular2,读什么:ViewChild 中使用的属性? [复制]
【发布时间】:2016-10-16 20:27:27
【问题描述】:

我理解并经常使用@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);    
      })

  }
}

问候

肖恩

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    这是一个示例:

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

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 2011-07-21
      • 2016-09-23
      • 2021-01-05
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      相关资源
      最近更新 更多