【问题标题】:Access template reference inside a template element访问模板元素内的模板引用
【发布时间】:2017-07-20 22:41:20
【问题描述】:

我正在使用一个库,它希望我将指令的主体指定为 template 元素的子元素

<template customDirective>
   <custom-element #lookup></custom-element>
</template>

有没有办法在我的组件中访问custom-element#lookup

例如,

@Component({
  selector: 'app-test',
  template: `
    <template customDirective>
       <custom-element #lookup></custom-element>
    </template>
  `
})
export class TestComponent {
  @ViewChild('lookup') viewChildRef;
  @ContentChild('lookup') contentChildRef;

  constructor() {
  }

  ngAfterContentInit(): void {
     console.log(this.viewChildRef); // <-- undefined
     console.log(this.contentChildRef); // <-- undefined
  }
}

在这两种情况下我都会收到undefined

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    尝试在ngAfterViewInit回调中查看lookedUpCustomElemRef

    https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

    【讨论】:

      【解决方案2】:

      在不创建嵌入视图之前,您无法获取对模板内组件的引用。

      尝试使用像这样的设置器:

      @ViewChild('lookup') 
      set lookUp(ref: any) {
        console.log(ref);
      }
      

      Plunker Example

      【讨论】:

      • 看起来它是在调用 ngAfterViewInit() 之前设置的。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2017-12-04
      相关资源
      最近更新 更多