我正在学习Angular 2。
我想使用@ViewChild Annotation从父组件访问子组件。
下面是一些代码行:
在< >强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>
FilterTiles.html模板被正确加载到ico-filter-tiles标签(确实我能够看到标题)。
注意:BodyContent
类使用DynamicComponetLoader: dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector)
注入到另一个模板(Body)中:
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模板。
有什么建议吗?