我正在嘗試學(xué)習(xí)Angular 2。我想使用@ViewChild Annotation 從父組件訪問(wèn)子組件。下面是幾行代碼:在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中時(shí): 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標(biāo)記中(實(shí)際上,我能夠看到標(biāo)頭)。注意:BodyContent類使用DynamicComponetLoader注入到另一個(gè)模板(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]})問(wèn)題是,當(dāng)我嘗試寫(xiě)入ft控制臺(tái)日志時(shí),我得到了undefined,當(dāng)然,當(dāng)我嘗試將某些內(nèi)容推入“ tiles”數(shù)組中時(shí),我當(dāng)然會(huì)遇到異常:“ no屬性tile為“ undefined””。還有一件事:FilterTiles組件似乎已正確加載,因?yàn)槲夷軌蚩吹剿膆tml模板。有什么建議嗎?謝謝
Angular 2 @ViewChild批注返回未定義
千萬(wàn)里不及你
2019-11-08 12:54:11