【问题标题】:export const values not binding in dropdown导出 const 值在下拉列表中未绑定
【发布时间】:2019-02-08 19:22:40
【问题描述】:

我在单独的文件中有一个常量值并绑定下拉选项中的值,工作日工作正常,但间隔时间将其绑定为对象对象 这是常量值.ts

工作正常

 export const weekdays =['sunday','Monday','Tuesday','wednesday','thursday'];

不工作

   export const IntervalTime =[{key:0,value:'10.00'},{key:1,value:'11.00'}];

组件.ts

 import {Component,OnInit} from '@angular/core';
    import {weekdays} from './constantvalues';
      /**
     * @title Basic select
     */
    @Component({
      selector: 'select-overview-example',
      templateUrl: 'select-overview-example.html',
      styleUrls: ['select-overview-example.css'],
    })
    export class SelectOverviewExample implements OnInit {
      days=[];
    
//not working[![enter image description here][1]][1]
    
    times =[];


ngOnInit(){
  [...this.days] = weekdays;
  [...this.times]=IntervalTime;
}
    }

html:
     <mat-form-field>
      <mat-select placeholder="select Weekdays">
        <mat-option *ngFor="let day of days" [value]="day">
          {{day}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <hr/> Second Dropdrown with Array of object
    
    <mat-form-field>
      <mat-select placeholder="select Weekdays">
        <mat-option *ngFor="let time of times" [value]="time">
          {{time}}
        </mat-option>
      </mat-select>
    </mat-form-field>

demo

【问题讨论】:

    标签: angular angular6 angular2-forms


    【解决方案1】:

    你应该分配time.value,而不是整个对象

    <mat-form-field>
      <mat-select placeholder="select Weekdays">
        <mat-option *ngFor="let time of times" [value]="time">
          {{time.value}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    分叉demo

    【讨论】:

    • 这是一种更好的方法,我有 10 个时间值,例如 10,11,12.... 因为我必须创建接口或模型来设置类型或设置像这样或 const 是更好;eg)foods: Food[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'} ];
    • 如果这些值没有改变(time 应该是这种情况),那么使用constants 是个好主意。当您想修改它们的属性时,Interface 或 model 很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多