Angular 2 @ViewChild 注释返回未定义

新手上路,请多包涵

我正在尝试学习 Angular 2。

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

这里有几行代码:

BodyContent.ts 我有:

 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(){};
 }

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

正文内容.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.loadAsRoot(BodyContent, '#ico-bodyContent', injector) )中:

 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 写入控制台日志时,我得到 undefined ,当然当我尝试在“tiles”数组中推送一些东西时我得到一个异常: ‘没有“未定义”的属性图块’

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

有什么建议么?

原文由 Andrea Ialenti 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 681
2 个回答

我有一个类似的问题,并认为我会发布以防其他人犯同样的错误。首先,要考虑的一件事是 AfterViewInit ;您需要等待视图初始化,然后才能访问您的 @ViewChild 。但是,我的 @ViewChild 仍然返回 null。问题是我的 *ngIf*ngIf 指令正在杀死我的控件组件,因此我无法引用它。

 import { Component, ViewChild, OnInit, AfterViewInit } from 'angular2/core';
import { ControlsComponent } from './controls/controls.component';
import { SlideshowComponent } from './slideshow/slideshow.component';

@Component({
  selector: 'app',
  template: `
    <controls *ngIf="controlsOn"></controls>
    <slideshow (mousemove)="onMouseMove()"></slideshow>
  `,
  directives: [SlideshowComponent, ControlsComponent],
})
export class AppComponent {
  @ViewChild(ControlsComponent) controls: ControlsComponent;

  controlsOn: boolean = false;

  ngOnInit() {
    console.log('on init', this.controls);
    // this returns undefined
  }

  ngAfterViewInit() {
    console.log('on after view init', this.controls);
    // this returns null
  }

  onMouseMove(event) {
    this.controls.show();
    // throws an error because controls is null
  }
}

希望有帮助。

编辑

正如 下面@Ashg 所述,解决方案是使用 @ViewChildren 而不是 @ViewChild

原文由 kenecaswell 发布,翻译遵循 CC BY-SA 4.0 许可协议

除了其他答案之外,您还可以使用最后一个生命周期挂钩:

 ngAfterViewChecked() {}

ngAfterViewChecked 甚至在 ngAfterViewInit 之后被调用

生命周期钩子: https ://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence

原文由 eko 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进