typescript 为 mat-select 预选多个值 - Angular 6

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53491710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:43:34  来源:igfitidea点击:

Preselecting multiple values for mat-select - Angular 6

htmlangulartypescriptangular-material

提问by Rana

I'm trying to preselect multiple options in a mat-select. So far I'm not able to achieve this.

我正在尝试在 mat-select 中预选多个选项。到目前为止,我无法实现这一目标。

Here is the HTML file:

这是 HTML 文件:

<mat-dialog-content [formGroup]="form">
   <mat-form-field>
     <mat-select placeholder="participants" formControlName="participants"  multiple>
         <mat-option *ngFor="let participant of participants" [value]="participant">{{participant}}</mat-option>
     </mat-select>
    </mat-form-field>
</mat-dialog-content>

Here is the controller:

这是控制器:

export class EventViewModalComponent implements OnInit {
  form: FormGroup;
  calendarEvent: CalendarEvent;
  participants = [];

  constructor(private fb: FormBuilder,
    private participantService: ParticipantService,
    @Inject(MAT_DIALOG_DATA) event: CalendarEvent) 
    { 
    this.form = fb.group({
      title: [event.title, Validators.required],
      location: [event.meta.location, Validators.required],
      description: [event.meta.description, Validators.required],
      start: [event.start, Validators.required],
      end: [event.end, Validators.required],
      participants: [this.participants, Validators.required]
    });
    this.calendarEvent = event;
  }

  ngOnInit() {
    this.participantService.getAll().subscribe(data =>{
      for(let i = 0; i < data['length']; i++){
        this.participants.push(data[i]['name']);
      }
    })
  }
}

This currently selects all the values per default. Here's a screenshot of how it looks currently: enter image description here

这当前默认选择所有值。这是它当前外观的屏幕截图: 在此处输入图片说明

What I'm trying to achieve is having only Cindy and Jim preselected like this:

我想要实现的只是像这样预选 Cindy 和 Jim:

enter image description here

在此处输入图片说明

How can I achieve this? I've read through several SO questions and wasn't successful. Any help is appreciated

我怎样才能做到这一点?我已经阅读了几个 SO 问题,但没有成功。任何帮助表示赞赏

采纳答案by Commercial Suicide

I believe that the easiest way is to use [(ngModel)]directive (or a one-way binding, I'll cover it shortly later) to manipulate the value of mat-select: you can bind a variable, which contains elements you want to preselect, something like this:

我相信最简单的方法是使用[(ngModel)]指令(或单向绑定,稍后我将介绍它)来操作 的值mat-select:您可以绑定一个变量,其中包含要预选的元素,如下所示:

<mat-select placeholder="participants" formControlName="participants" multiple [(ngModel)]="selection">
  <mat-option *ngFor="let participant of participants" [value]="participant">{{participant}}</mat-option>
</mat-select>

And then you can just filter your initial array of items and get only those, which you want to select by default (it should be stored in selectionclass property in provided case).

然后你可以过滤你的初始项目数组,只获取那些你想要默认选择的项目(selection在提供的情况下,它应该存储在类属性中)。

I have created a STACKBLITZto demonstrate, that it's possible. In this example, I filter items at even indexes, and finally we get "1'st, 3'rd, 5'th, ..."items selected.

我创建了一个STACKBLITZ来证明这是可能的。在这个例子中,我在偶数索引处过滤项目,最后我们选择了“1'st, 3'rd, 5'th, ...”项目。

Notice, that you can split [(ngModel)]into 2 separate directives if you want to use only a one-way binding: [ngModel]or (ngModelChange). For more info, take a look at angular template syntax guide.

请注意,[(ngModel)]如果您只想使用单向绑定,则可以拆分为 2 个单独的指令:[ngModel](ngModelChange)。有关更多信息,请查看angular 模板语法指南

回答by intotecho

With Angular6+ there is a deprecation warning when you have both a formControl and [(ngModel)]

使用 Angular6+ 时,当您同时拥有 formControl 和 [(ngModel)] 时,会出现弃用警告

It looks like you're using ngModel on the same form field as formControl. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.

看起来您在与 formControl 相同的表单字段上使用 ngModel。Angular v6 中不推荐使用 ngModel 输入属性和 ngModelChange 事件与响应式表单指令,并将在 Angular v7 中删除。

Option 1 using [ngModel] without FormControl

选项 1 使用 [ngModel] 而不使用 FormControl

As the first answer suggests, split [ngModel] and (ngModelChange) like this.

正如第一个答案所暗示的那样,像这样拆分 [ngModel] 和 (ngModelChange)。

<mat-select 
  [ngModel]="selectedFoods" 
  (ngModelChange)="selectedFoods" 
  placeholder="Favorite food" multiple>
  <mat-option *ngFor="let food of allfoods" [value]="food.value">
      {{food.viewValue}}
  </mat-option>
</mat-select>

And for the ts.

而对于 ts。

  allfoods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'},
    {value: 'pasta-3', viewValue: 'Pasta'}
  ];
  selectedFoods = [
     'steak-0', 'pasta-3'
  ];

https://stackblitz.com/edit/angular-mat-select-with-ngmodel?embed=1&file=app/select-overview-example.ts

https://stackblitz.com/edit/angular-mat-select-with-ngmodel?embed=1&file=app/select-overview-example.ts

Option 2 using [formControl] without [ngModel]

选项 2 使用 [formControl] 而没有 [ngModel]

<mat-form-field>
    <mat-select [formControl]="foodForm" placeholder="Favorite food" multiple>
        <mat-option *ngFor="let food of allfoods" [value]="food.value">
            {{food.viewValue}}
        </mat-option>
    </mat-select>
</mat-form-field>

In this case, the selection is initialised in the FormControl's constructor.

在这种情况下,选择在 FormControl 的构造函数中初始化。

 allfoods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'},
    {value: 'pasta-3', viewValue: 'Pasta'}
    ];
 myselectedFoods = ['pasta-3', 'steak-0'];
 foodForm: FormControl = new FormControl(this.myselectedFoods);

https://stackblitz.com/edit/angular-mat-select-multi-with-formcontrol

https://stackblitz.com/edit/angular-mat-select-multi-with-formcontrol