问题

在显示模板中的相应元素后,获得@ViewChild的最优雅方式是什么?

下面是一个示例.也有Plunker个可用.

Component.template.html:

<div id="layout" *ngIf="display">
  <div #contentPlaceholder></div>
</div>

Component.component.ts:

export class AppComponent {

    display = false;
    @ViewChild('contentPlaceholder', { read: ViewContainerRef }) viewContainerRef;

    show() {
        this.display = true;
        console.log(this.viewContainerRef); // undefined
        setTimeout(() => {
            console.log(this.viewContainerRef); // OK
        }, 1);
    }
}

我有一个默认隐藏其内容的组件.当有人调用show()方法时,它变得可见.但是,在Angular 2变化检测完成之前,我不能参考viewContainerRef.我通常将所有必需的操作包装到setTimeout(()=>{},1)中,如上所示.有没有更正确的方法?

我知道有一个选项有ngAfterViewChecked个,但它会导致太多无用的电话.

回答(柱塞)

推荐答案

使用ViewChild的setter:

 private contentPlaceholder: ElementRef;

 @ViewChild('contentPlaceholder') set content(content: ElementRef) {
    if(content) { // initially setter gets called with undefined
        this.contentPlaceholder = content;
    }
 }

一旦*ngIf变为true,setter就会被元素引用调用.

注意,对于Angular 8,必须确保设置{ static: false },这是其他Angular版本中的默认设置:

 @ViewChild('contentPlaceholder', { static: false })

注意:如果contentPlaceholder是组件,则可以将ElementRef更改为组件类:

  private contentPlaceholder: MyCustomComponent;

  @ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
     if(content) { // initially setter gets called with undefined
          this.contentPlaceholder = content;
     }
  }

Angular相关问答推荐

Angular:浏览器中未显示一些Google Content图标

间歇性不正确的SSR重定向(server. ts级别的请求和响应不匹配)

Angular 15:将数据从主零部件传递到辅零部件

如何通过innerHtml在模板中显示动态插入的动感图标?

如果Rxjs间隔请求仍在进行,则不应重置,但如果用户更改输入,则应重置

基于RxJS的Angular 服务数据缓存

在以下位置升级到Angular 16 Break Sharepoint广告:This._history.replaceState不是函数

显示用户名-Angular

Nx Angular Monorepo 中 cypress 组件测试的代码覆盖率?

如何根据响应变化更改 Angular Carousel 的cellsToShow

BehaviorSubject 在 Angular 中制作数据之间的时间表(或计时器)

如何在Angular中自动路由到子路由

关闭 Dynamsoft Web Twain 弹出窗口

Angular模板错误:Property does not exist on type component

当我ng serve时,Angular CLI 提示TypeError: callbacks[i] is not a function

Angular2 路由 VS ui-router-ng2 VS ngrx 路由

Angular2 Pipes:输出原始 HTML

如何每隔一段时间发出 HTTP 请求?

Angular 中 polyfills.ts 文件有什么用

具有多个订阅者的 Angular 2 Observable