问题

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

下面是一个例子。也可提供活塞。

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有一个选项,但它会导致太多无用的调用。

答案(设置)


当前回答

只需确保静态选项设置为false

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

其他回答

上面的答案并不适用于我,因为在我的项目中,ngIf是在一个输入元素上。我需要访问nativeElement属性,以便在ngIf为真时专注于输入。在ViewContainerRef上似乎没有nativeElement属性。以下是我所做的(遵循@ViewChild文档):

<button (click)='showAsset()'>Add Asset</button>
<div *ngIf='showAssetInput'>
    <input #assetInput />
</div>

...

private assetInputElRef:ElementRef;
@ViewChild('assetInput') set assetInput(elRef: ElementRef) {
    this.assetInputElRef = elRef;
}

...

showAsset() {
    this.showAssetInput = true;
    setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });
}

我在聚焦之前使用了setTimeout,因为ViewChild需要一秒来分配。否则就没有定义了。

简化版,我在使用谷歌Maps JS SDK时遇到了类似的问题。

我的解决方案是将divand ViewChild提取到它自己的子组件中,当在父组件中使用时,可以使用*ngIf隐藏/显示。

之前

HomePageComponent模板

<div *ngIf="showMap">
  <div #map id="map" class="map-container"></div>
</div>

HomePageComponent组件

@ViewChild('map') public mapElement: ElementRef; 

public ionViewDidLoad() {
    this.loadMap();
});

private loadMap() {

  const latLng = new google.maps.LatLng(-1234, 4567);
  const mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };
   this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}

public toggleMap() {
  this.showMap = !this.showMap;
 }

MapComponent模板

 <div>
  <div #map id="map" class="map-container"></div>
</div>

MapComponent组件

@ViewChild('map') public mapElement: ElementRef; 

public ngOnInit() {
    this.loadMap();
});

private loadMap() {

  const latLng = new google.maps.LatLng(-1234, 4567);
  const mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };
   this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}

HomePageComponent模板

<map *ngIf="showMap"></map>

HomePageComponent组件

public toggleMap() {
  this.showMap = !this.showMap;
 }

对于Angular 8——混合了null检查和@ViewChild static:错误的黑客

用于等待异步数据的分页控件

@ViewChild(MatPaginator, { static: false }) set paginator(paginator: MatPaginator) {
  if(!paginator) return;
  paginator.page.pipe(untilDestroyed(this)).subscribe(pageEvent => {
    const updated: TSearchRequest = {
      pageRef: pageEvent.pageIndex,
      pageSize: pageEvent.pageSize
    } as any;
    this.dataGridStateService.alterSearchRequest(updated);
  });
}

另一个快速的“技巧”(简单的解决方案)是使用[hidden]标签而不是*ngIf,重要的是要知道,在这种情况下,Angular会构建对象并在类下绘制它:隐藏,这就是ViewChild工作没有问题的原因。 所以重要的是要记住,你不应该在沉重或昂贵的物品上使用隐藏,这会导致性能问题

  <div class="addTable" [hidden]="CONDITION">

正如其他人提到的,最快的解决方案是使用[hidden]而不是*ngIf。采用这种方法,组件将被创建但不可见,因此您可以访问它。这可能不是最有效的方法。