I use angular 9 and have this form with a select. This select is a list of countries. I can see the countries list in my console.
<div class="card mb-5">
<div class="card-body">
<aw-wizard #companyCreationWizard>
<aw-wizard-step stepTitle="{{ 'company.wizard-information' | translate }}" style="min-height: 120px;">
<form #companyCreationForm="ngForm" novalidate (ngSubmit)="onSubmit()">
<div class="row">
<div class="col-6">
<label class="form-group has-float-label">
<input class="form-control" required ngModel #name="ngModel" name="name"/>
<span>{{ 'company.name' | translate }}</span>
<div *ngIf="!name.valid && registerForm.submitted" class="invalid-tooltip">Name is required!</div>
</label>
</div>
<div class="col-6">
<label class="form-group has-float-label">
<ng-select [items]="countries" bindLabel="name" name="countryCode" bindValue="countryCode" [(ngModel)]="selectedCountryCode">
</ng-select>
<span>{{ 'company.country' | translate }}</span>
</label>
</div>
</div>
<div class="justify-content-between align-items-center">
<app-state-button [btnClass]="'btn btn-primary btn-lg btn-shadow wizard-button-right'" [currentState]="buttonState"
[isDisabled]="buttonDisabled" click="onLoginClick()">
{{ 'company.create' | translate | uppercase }}
</app-state-button>
</div>
</form >
</aw-wizard-step>
</aw-wizard >
</div>
</div>
When I try to inject data to initialize the ng-select I have 0 data in my list. My component file looks like:
export class CompanyCreationComponent implements OnInit {
@ViewChild('companyCreationForm') registerForm: NgForm;
countries: Country[];
selectedCountryCode = 'FR';
constructor(
private authService: AuthService,
private contryService: CountryControllerService) {
this.contryService.findAllCountriesUsingGETResponse().subscribe({
next(countriesResponse) {
console.log(countriesResponse.body); // I have a list of countries here
this.countries = countriesResponse.body;
},
error(error) {
console.log(error);
}
});
}
My countries list looks like:
[
{
"countryCode": "AD",
"name": "Andorra",
"indicatif": "+376"
},
{
"countryCode": "AE",
"name": "United Arab Emirates",
"indicatif": "+971"
},
{
"countryCode": "AF",
"name": "Afghanistan",
"indicatif": "+93"
},
{
"countryCode": "AG",
"name": "Antigua and Barbuda",
"indicatif": "+1268"
},
{
"countryCode": "AI",
"name": "Anguilla",
"indicatif": "+1264"
}...]
What did I do wrong ? Thanks in advance.
The problem is due to how i get the response. With angular 9, I should use the observable like this :
ngOnInit() {
this.contryService.findAllCountriesUsingGETResponse().subscribe(
(countriesResponse) => {
this.countries = countriesResponse.body;
},
(error) => {
this.notifications.create(
'Error',
error.message,
NotificationType.Error,
{ theClass: 'outline primary', timeOut: 6000, showProgressBar: false }
);
this.buttonDisabled = false;
this.buttonState = '';
});
}