首页 文章

如何将值设置为多个mat-select in angular 4

提问于
浏览
0

我有一个mat-select,带有多个选择选项(复选框),角度为4

在HTML中

<mat-form-field>
     <mat-select placeholder="Location" [formControl]="toppings"  [(ngModel)]="locSelected" multiple>
                  <mat-option *ngFor="let topping of loc; let i = index" [value]="topping.value">
                    {{topping.viewValue}}</mat-option>
                </mat-select>
              </mat-form-field>

在ts文件中

locSelected:Array<string>=[];
        loc= [
        { value: '1', viewValue: 'US' },
        { value: '2', viewValue: 'UK' },
        { value: '3', viewValue: 'Europe' },
        {value:'4',viewValue:'London'},
        {value:'5',viewValue:'France'},
        {value:'6',viewValue:'Italy'},
        {value:'7',viewValue:'Others'} ];

我从WebAPI结果中获取所选值 . 我尝试过使用[(ngModel)],但它没有用 .

从WebApi结果

if(result.locSelectedValue!="" && result.locSelectedValue!=null)
 {
   let location=result.locSelectedValue.split(",");
   for(var i=0;i<location.length;i++)
   {
    this.locSelected.push(loc[i]);
   } 
 }

我将从WebApi获得的结果将采用以下格式:3,5,6

因此应选择欧洲,法国,意大利复选框的值 .

如何实现这一目标 . 我是角度4的新手 .

3 回答

  • 0

    由于您已经在使用 [formControl] ,因此无需使用 ngModel . 从API获取记录后,您可以将值设置为formControl,它将负责休息 .

    修改代码 -

    toppings = new FormControl(); //You might have already
    
    if(result.locSelectedValue!="" && result.locSelectedValue!=null)
     {
       let location=result.locSelectedValue.split(",");
       for(var i=0;i<location.length;i++)
       {
        this.locSelected.push(loc[i]);
       } 
      this.toppings.setValue(this.locSelected); //This will update your UI
     }
    

    不要忘记从html中删除ngModel

  • 0

    我认为多选下拉列表非常适合您的要求 .

    https://www.npmjs.com/package/ng-multiselect-dropdown

  • 0

    这是我的答案 . 您可以从Web API获取toppingList . 在这里它是硬编码的 .

    在你的.html中,

    <mat-form-field>
      <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
        <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
      </mat-select>
    </mat-form-field>
    

    在你的.ts中

    export class SelectMultipleExample {
      toppings = new FormControl();
      toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
    }
    

相关问题