我正在学习Angular 2。

我想使用@ViewChild Annotation从父组件访问子组件。

下面是一些代码行:

在BodyContent。我有:

import { ViewChild, Component, Injectable } from 'angular2/core';
import { FilterTiles } from '../Components/FilterTiles/FilterTiles';

@Component({
    selector: 'ico-body-content',
    templateUrl: 'App/Pages/Filters/BodyContent/BodyContent.html',
    directives: [FilterTiles] 
})
export class BodyContent {
    @ViewChild(FilterTiles) ft: FilterTiles;

    public onClickSidebar(clickedElement: string) {
        console.log(this.ft);
        var startingFilter = {
            title: 'cognomi',
            values: [ 'griffin', 'simpson' ]
        }
        this.ft.tiles.push(startingFilter);
    } 
}

FilterTiles.ts:

 import { Component } from 'angular2/core';

 @Component({
     selector: 'ico-filter-tiles',
     templateUrl: 'App/Pages/Filters/Components/FilterTiles/FilterTiles.html'
 })
 export class FilterTiles {
     public tiles = [];

     public constructor(){};
 }

最后是模板(在评论中建议):

BodyContent.html

<div (click)="onClickSidebar()" class="row" style="height:200px; background-color:red;">
    <ico-filter-tiles></ico-filter-tiles>
</div>

FilterTiles.html

<h1>Tiles loaded</h1>
<div *ngFor="#tile of tiles" class="col-md-4">
     ... stuff ...
</div>

FilterTiles.html模板被正确加载到ico-filter-tiles标签(确实我能够看到标题)。

注意:BodyContent类使用DynamicComponetLoader: dcl注入到另一个模板(Body)中。loadAsRoot(BodyContent, '#ico-bodyContent',注入器):

import { ViewChild, Component, DynamicComponentLoader, Injector } from 'angular2/core';
import { Body } from '../../Layout/Dashboard/Body/Body';
import { BodyContent } from './BodyContent/BodyContent';

@Component({
    selector: 'filters',
    templateUrl: 'App/Pages/Filters/Filters.html',
    directives: [Body, Sidebar, Navbar]
})
export class Filters {

    constructor(dcl: DynamicComponentLoader, injector: Injector) {
       dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector);
       dcl.loadAsRoot(SidebarContent, '#ico-sidebarContent', injector);
   } 
}

问题是,当我试图将ft写入控制台日志时,我得到了未定义,当然,当我试图在“tiles”数组内推一些东西时,我会得到一个异常:“没有属性瓷砖”。

还有一件事:FilterTiles组件似乎正确加载,因为我能够看到它的html模板。

有什么建议吗?


当前回答

在我的例子中,我有一个使用ViewChild的输入变量setter,而ViewChild在*ngIf指令中,所以setter试图在*ngIf渲染之前访问它(没有*ngIf它可以正常工作,但如果它总是被*ngIf="true"设置为真,它就不会工作)。

为了解决这个问题,我使用Rxjs来确保任何对ViewChild的引用都要等到视图被初始化。首先,创建一个在view init之后完成的Subject。

export class MyComponent implements AfterViewInit {
  private _viewInitWaiter$ = new Subject();

  ngAfterViewInit(): void {
    this._viewInitWaiter$.complete();
  }
}

然后,创建一个在主题完成后接受并执行lambda的函数。

private _executeAfterViewInit(func: () => any): any {
  this._viewInitWaiter$.subscribe(null, null, () => {
    return func();
  })
}

最后,确保对ViewChild的引用使用了这个函数。

@Input()
set myInput(val: any) {
    this._executeAfterViewInit(() => {
        const viewChildProperty = this.viewChild.someProperty;
        ...
    });
}

@ViewChild('viewChildRefName', {read: MyViewChildComponent}) viewChild: MyViewChildComponent;

其他回答

这里有一些对我有用的东西。

@ViewChild('mapSearch', { read: ElementRef }) mapInput: ElementRef;

ngAfterViewInit() {
  interval(1000).pipe(
        switchMap(() => of(this.mapInput)),
        filter(response => response instanceof ElementRef),
        take(1))
        .subscribe((input: ElementRef) => {
          //do stuff
        });
}

所以我基本上每秒钟设置一次检查,直到*ngIf变成true,然后我做与ElementRef相关的事情。

只是添加{static: true} @View解决了我的问题。

@ViewChild(FilterTiles, { static : true }) ft: FilterTiles;

我有一个类似的问题,在ViewChild被引用之前,ViewChild在一个switch子句中没有加载ViewChild元素。我以一种半hack的方式解决了这个问题,但将ViewChild引用包装在立即执行的setTimeout中(即0ms)

你可以为@ViewChild()使用setter

@ViewChild(FilterTiles) set ft(tiles: FilterTiles) {
    console.log(tiles);
};

如果你有一个ngIf包装器,setter将被undefined调用,然后在ngIf允许它呈现时再次被引用调用。

但我的问题是另一回事。我没有在我的app.modules中包含我的“FilterTiles”模块。模板没有抛出错误,但是引用总是未定义的。

如果一个*ngIf="show"阻止ViewChild被渲染,并且在你的show变为true后你需要ViewChild,它帮助我在我设置show为true后立即触发ChangeDetectorRef.detectChanges()。

在此之后,*ngIf创建组件并渲染ViewChild,你可以在之后使用它。只是输入了一个快速的示例代码。

@ViewChild(MatSort) sort: MatSort;    

constructor(private cdRef: ChangeDetectorRef) {}

ngOnInit() {
  this.show = false;
  this.someObservable()
    .pipe(
      tap(() => {
        this.show = true;
        this.cdRef.detectChanges();
      })
    )
    .subscribe({
      next: (data) => {
        console.log(sort)
        this.useResult(data);
      }
    });
}

这是坏事吗?还是为什么没有人提出?