提问者:小点点

Angular 2@ViewChild注释返回未定义


我正在学习《棱角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(){};
 }

最后,这里是模板(如注释中所建议的):

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>

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

注意:使用DynamicComponetLoader将BodyContent类注入到另一个模板(Body)中: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”数组中推入一些东西时,我得到了一个异常:“no property tiles for”undefined“”。

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

有什么建议吗?谢谢


共1个答案

匿名用户

我有一个类似的问题,我想我会发帖,以防别人犯同样的错误。首先,要考虑的一件事是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在下面提到的,一个解决方案是使用@viewchildr而不是@viewchildr