我正在尝试学习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注入到另一个模板(Body)内:dcl.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
控制台日志时,我得到了undefined
,当然,当我尝试将某些内容推入“ tiles”数组中时,我当然会遇到异常:“ no属性tile为“ undefined””。
还有一件事:FilterTiles组件似乎已正确加载,因为我能够看到它的html模板。
有什么建议吗?谢谢
ft
不会在构造函数中设置,但在click事件处理程序中将已经设置。
loadAsRoot
。一旦我替换loadIntoLocation
为问题就解决了。如果您将您的评论作为答案,我可以将其标记为接受