嵌套在ngIf中的组件的Angular2 @ViewChild错误

时间:2017-05-04 19:05:01

标签: angular typescript

我正在使用ng2-select。要动态获取数据,请遵循以下方法:

https://github.com/valor-software/ng2-select/issues/635

首先我选择这样的组件:

HTML:

<form #frecipientAddAccount="ngForm" novalidate>
     <ng-select #recipientBanks (selected)="selected($event)" placeholder="Select Bank"></ng-select>

componen.ts:

@ViewChild('recipientBanks') recipientBanks: SelectComponent

我使用提取的数据创建选项元素,如下所示:

ngOnInit(): void {
    (<any>this.recipientBanks).items = []
    let currencyTypeId = this.determineCurrencyType();
    let response = getRecipientBanksForCountry(this.data.dashboard.userCountryId, 'C', currencyTypeId);
    response.then((data) => {
        (<any>this.recipientBanks).items = data.list.map(function (obj) {
            return new SelectOptionComponent(obj.BankId, obj.Description)
        })
    })
}

到目前为止它正在发挥作用。问题是ng-select元素需要嵌套在几个ngIf元素中,但如果我这样做,突然组件(<any>this.recipientBanks)未定义。

如果组件嵌套在ngIf s?

中,我怎么还能选择它?

2 个答案:

答案 0 :(得分:3)

而不是在div中使用#recipientBanks,而不是如下所示,

@ViewChild(SelectComponent) recipientBanks: SelectComponent

更新1:

除了使用ViewChild对象并分配属性,您可以使用不同的对象,因为ViewChild()结果是未定义的,除非它在DOM中呈现

 <ng-select #recipientBanks (selected)="selected($event)" [items]="dropDownItems" placeholder="Select Bank"></ng-select>

将数据分配到dropDownItems变量而不是<any>this.recipientBanks).items

或者,您可以使用[hidden]代替*ngIf

答案 1 :(得分:0)

我将ngOnInit替换为ngAfterViewInit,现在可以了!

相关问题