简体   繁体   中英

Mat-select doesnt display the array content in ngfor

I have an array of countries and i want to display in a mat-select list of options. I am receiving the data like an object format in this.lngCountries so i need to convert to array first.

I think that the array is not complete before the ngfor is loaded. How can I wait for my function to finish? Because my problem is that when the page loads the ngfor my array is still empty.

My code:

private preparePaisOpts() {
        let array = this.lngCountries;
        this.paisOps = Object.keys(array).map(function(index) {
            let count = array[index];
            return count;
        });        
}

HTML:

<th2-mat-select class="form-field-dark" required [form]="usecaseForm"
    formControlFieldName="pais" 
    placeholder="País">
    <mat-option *ngFor="let country of paisOps" [value]="country">{{country}}</mat-option>
</th2-mat-select>

Thanks!!! <3

One way is ngIf

<th2-mat-select *ngIf="paisOps && paisOps.length > 0" class="form-field-dark" required [form]="usecaseForm"
    formControlFieldName="pais" 
    placeholder="País">
    <mat-option *ngFor="let country of paisOps" [value]="country">{{country}}</mat-option>
</th2-mat-select>

Better is to show a loading spinner instead of the select as example for a better user experience.

You can set a custom variable, too:

loading: boolean = true;

...

private preparePaisOpts() {
        let array = this.lngCountries;
        this.paisOps = Object.keys(array).map(function(index) {
            let count = array[index];
            return count;
        });
        
        this.loading = false;
}

and HTML

<th2-mat-select *ngIf="!loading" class="form-field-dark" .......

But!

Normally ngFor will be refresh the data if it's array changing. You write not specific error so I don't know what your problem is.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM