简体   繁体   中英

Data is loading after binding in template angular 5

After some manipulation on data, I am getting response in console like this:

[{"date":"02-01-2018 - 31-12-2018"},{"date":"01-07-2018 - 31-12-2018"}]

But when I am trying to display this value in drop down, nothing is showed, its seems data binding happens before data loading. kindly help

Here is my code

Change(opened: boolean) {
    if (opened) { }     
    var rvaldata:any= [];

    calculateRange(this.choosenSub);
    if(rvaldata!='')
    {
    this.nrvaldata=JSON.stringify(rvaldata);
    console.log(this.nrvaldata);
    }
    function calculateRange(_data){
    var r = "";
    for(var i=0;i<_data.length;i++){
       var isArray = Array.isArray(_data[i]);
       if(isArray){
        r+=calculateRange(_data[i]);
       }else{
        var x = _data[i].date;
        r = rvaldata.push({'date':x})
        }
      }
      return JSON.stringify(r);
      }  
}

Here is my html

<div  class="d-inline-block">
<span class="plabel">Date<span class="star">*</span></span>
<mat-form-field>
<mat-select placeholder="Validity" class="project-tab" [formControl]="toppings" multiple required>
<ng-template >
<mat-option *ngFor="let t of nrvaldata; let i = index" [value]="t.date">{{t.date}}</mat-option>
</ng-template>
</mat-select>
</mat-form-field>
</div>

Kindly help

The problem in your code is the <ng-template> directive ng-template s are like function they are not executed unless called in other words they are not displayed unless you call *ngIf="true" to them or use them for a template to other container using expression.

Remove the ng-template around mat-option

<div  class="d-inline-block">
<span class="plabel">Date<span class="star">*</span></span>
<mat-form-field>
<mat-select placeholder="Validity" class="project-tab" [formControl]="toppings" multiple required>
<mat-option *ngFor="let t of nrvaldata; let i = index" [value]="t.date">{{t.date}}</mat-option>
</mat-select>
</mat-form-field>
</div>

*ngFor expects an array, but because you're calling JSON.stringify you're actually passing it a string. If you check in the browsers console you will probably see an error about this.

Just replace

this.nrvaldata=JSON.stringify(rvaldata);

with

this.nrvaldata=rvaldata;

Also, remove the ng-template tags and you should find it will work.

Here is a StackBlitz of it in action

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