I'm working with ng2-select. To fetch the data dynamically, I'm following this method:
https://github.com/valor-software/ng2-select/issues/635
So first I select the component like so:
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.
How can I still select the component when it is nested in ngIf
s?
Instead of having the #recipientBanks
in the div use it as below,
@ViewChild(SelectComponent) recipientBanks: SelectComponent
Update 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
<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
Alternatively you can use [hidden]
instead of *ngIf
我将ngOnInit
替换为ngAfterViewInit
,现在它可以工作了!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.