[英]Angular2 @ViewChild error for component nested in ngIf
I'm working with ng2-select. 我正在使用ng2-select。 To fetch the data dynamically, I'm following this method:
要动态获取数据,我正在遵循以下方法:
https://github.com/valor-software/ng2-select/issues/635 https://github.com/valor-software/ng2-select/issues/635
So first I select the component like so: 所以首先我选择这样的组件:
HTML: HTML:
<form #frecipientAddAccount="ngForm" novalidate>
<ng-select #recipientBanks (selected)="selected($event)" placeholder="Select Bank"></ng-select>
componen.ts: 组件:
@ViewChild('recipientBanks') recipientBanks: SelectComponent
And I create the option elements with the fetched data like so: 我用提取的数据创建选项元素,如下所示:
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)
})
})
}
And it is working so far. 到目前为止它正在发挥作用。 The problem is that the
ng-select
element needs to be nested in a couple of ngIf
elements, but if I do so, suddenly the component (<any>this.recipientBanks)
is undefined. 问题是
ng-select
元素需要嵌套在几个ngIf
元素中,但如果我这样做,突然组件(<any>this.recipientBanks)
是未定义的。
How can I still select the component when it is nested in ngIf
s? 当它嵌套在
ngIf
时,如何选择组件?
Instead of having the #recipientBanks
in the div use it as below, 而不是在div中使用
#recipientBanks
,而不是如下所示,
@ViewChild(SelectComponent) recipientBanks: SelectComponent
Update 1 : 更新1:
Instead of using the ViewChild object and assign the properties you can use different object as the ViewChild() turns out to be undefined unless it is rendered in the DOM 而不是使用ViewChild对象并分配属性,您可以使用不同的对象,因为ViewChild()结果是未定义的,除非它在DOM中呈现
<ng-select #recipientBanks (selected)="selected($event)" [items]="dropDownItems" placeholder="Select Bank"></ng-select>
Assign the data to dropDownItems
variable instead of <any>this.recipientBanks).items
将数据分配给
dropDownItems
变量而不是<any>this.recipientBanks).items
Alternatively you can use [hidden]
instead of *ngIf
或者,您可以使用
[hidden]
而不是*ngIf
我将ngOnInit
替换为ngAfterViewInit
,现在它可以工作了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.