亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular 2 @ViewChild批注返回未定義

Angular 2 @ViewChild批注返回未定義

千萬里不及你 2019-11-08 12:54:11
我正在嘗試學習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”的模塊。模板沒有引發錯誤,但是引用始終是未定義的。


查看完整回答
反對 回復 2019-11-08
  • 3 回答
  • 0 關注
  • 663 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號