我正在嘗試學習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]})問題是,當我嘗試寫入ft控制臺日志時,我得到了undefined,當然,當我嘗試將某些內容推入“ tiles”數組中時,我當然會遇到異常:“ no屬性tile為“ undefined””。還有一件事:FilterTiles組件似乎已正確加載,因為我能夠看到它的html模板。有什么建議嗎?謝謝
3 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
您可以使用二傳手 @ViewChild()
@ViewChild(FilterTiles) set ft(tiles: FilterTiles) {
console.log(tiles);
};
如果您具有ngIf包裝器,則將使用未定義的setter進行調用,然后使用ngIf允許其呈現的引用再次進行調用。
我的問題是別的。我沒有在我的app.modules中包含包含“ FilterTiles”的模塊。模板沒有引發錯誤,但是引用始終是未定義的。
- 3 回答
- 0 關注
- 663 瀏覽
添加回答
舉報
0/150
提交
取消