Angular 2 @ViewChild批注返回未定义 [英] Angular 2 @ViewChild annotation returns undefined

查看:76
本文介绍了Angular 2 @ViewChild批注返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Angular 2.

I am trying to learn Angular 2.

我想使用 @ViewChild 注释从父组件访问子组件.

I would like to access to a child component from a parent component using the @ViewChild Annotation.

下面是几行代码:

BodyContent.ts 中,我有:

In BodyContent.ts I have:

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 中:

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

最后是模板(如注释中所建议):

Finally here the templates (as suggested in comments):

BodyContent.html

BodyContent.html

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

FilterTiles.html

FilterTiles.html

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

FilterTiles.html模板已正确加载到 ico-filter-tiles 标记中(实际上,我能够看到标题).

FilterTiles.html template is correctly loaded into ico-filter-tiles tag (indeed I am able to see the header).

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

Note: the BodyContent class is injected inside another template (Body) using 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"数组中时,也会出现异常:'没有针对未定义"的属性图块..

The problem is that when I try to write ft into the console log, I get undefined, and of course I get an exception when I try to push something inside the "tiles" array: 'no property tiles for "undefined"'.

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

One more thing: FilterTiles component seems to be correctly loaded, since I'm able to see the html template for it.

有什么建议吗?谢谢

推荐答案

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

I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit; you need to wait for the view to be initialized before you can access your @ViewChild. However, my @ViewChild was still returning null. The problem was my *ngIf. The *ngIf directive was killing my controls component so I couldn't reference it.

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.

EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren instead of @ViewChild.

这篇关于Angular 2 @ViewChild批注返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆