【问题标题】:ViewChild vs Directive to get ViewContainerRefViewChild vs Directive 获取 ViewContainerRef
【发布时间】:2020-03-22 11:56:25
【问题描述】:

我发现 Angular Docs 建议为了访问 ViewContainerRef 来创建动态组件,我应该使用如下指令:

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]',
})
export class AdDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

然后在组件中:

export class AppComponent {  
  @ViewChild(AdDirective, {static: true}) adHost: AdDirective;

... //to get access to ViewContainerRef
const viewContainerRef = this.adHost.viewContainerRef;

但是,如果没有指令,我可以通过使用 ViewChild{read : ViewContainerRef} 来实现相同的效果,例如:

export class AppComponent {

  @ViewChild('someHashTag', {read : ViewContainerRef}) target: ViewContainerRef;

这两种方法之间是否存在任何差异(可能的问题),或者我为什么不应该使用需要较少代码和工作量的方法?

【问题讨论】:

    标签: angular typescript angular-components


    【解决方案1】:

    不确定您是否仍在尝试解决此问题,但我已经能够使用如下指令获取 ViewContainerRef:

    @ViewChild(AdDirective, {static: true, read: ViewContainerRef}) target: ViewContainerRef;
    

    【讨论】:

      【解决方案2】:

      使用指令,您将仅在指令第一次出现时获得 vcref。 如果您希望 vcRef 用于 Dom 中的多个位置,那么 @viewchild() 将很有用。

      【讨论】:

        猜你喜欢
        • 2017-10-27
        • 1970-01-01
        • 2022-12-15
        • 1970-01-01
        • 2019-01-03
        • 2021-03-14
        • 2020-12-08
        • 2019-01-20
        • 2018-12-01
        相关资源
        最近更新 更多