我正在学习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模板。

有什么建议吗?


当前回答

在我的例子中,我知道子组件将始终存在,但希望在初始化子组件之前更改状态以节省工作。

我选择对子组件进行测试,直到它出现并立即进行更改,这为我节省了对子组件的更改周期。

export class GroupResultsReportComponent implements OnInit {

    @ViewChild(ChildComponent) childComp: ChildComponent;

    ngOnInit(): void {
        this.WhenReady(() => this.childComp, () => { this.childComp.showBar = true; });
    }

    /**
     * Executes the work, once the test returns truthy
     * @param test a function that will return truthy once the work function is able to execute 
     * @param work a function that will execute after the test function returns truthy
     */
    private WhenReady(test: Function, work: Function) {
        if (test()) work();
        else setTimeout(this.WhenReady.bind(window, test, work));
    }
}

注意,您可以为setTimeout添加一个最大尝试次数或添加几个ms的延迟。setTimeout有效地将函数抛出到挂起操作列表的底部。

其他回答

这对我来说是可行的,参见下面的示例。

import {Component, ViewChild, ElementRef} from 'angular2/core'; @Component({ selector: 'app', template: ` <a (click)="toggle($event)">Toggle</a> <div *ngIf="visible"> <input #control name="value" [(ngModel)]="value" type="text" /> </div> `, }) export class AppComponent { private elementRef: ElementRef; @ViewChild('control') set controlElRef(elementRef: ElementRef) { this.elementRef = elementRef; } visible:boolean; toggle($event: Event) { this.visible = !this.visible; if(this.visible) { setTimeout(() => { this.elementRef.nativeElement.focus(); }); } } }

我的解决方案是将ngIf从子组件的外部移动到子组件的内部,在一个div上包装了整个html部分。这样,当它需要隐藏时,它仍然被隐藏,但能够加载组件,我可以在父组件中引用它。

对我来说有效的解决方案是在app.module.ts的声明中添加指令

你可以为@ViewChild()使用setter

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

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

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

对我来说,问题是我引用了元素上的ID。

@ViewChild('survey-form') slides:IonSlides;

<div id="survey-form"></div>

而不是这样:

@ViewChild('surveyForm') slides:IonSlides;

<div #surveyForm></div>