我在 Angular 的 Mat-select 字段中创建全选选项并将 id 传递给另一个 ngModel 时遇到问题。
模板.html
<form [formGroup]="composeGroup"> <mat-form-field> <mat-select id="groupIds" formControlName="groupIds" multiple [(ngModel)]="composeCreateMessage.groupIds"> <mat-option (click)="selectAllGroups()">Select All</mat-option> <mat-option *ngFor="let group of groups; let i=index" [value]="groups[i].id">{{ group[i].name}}</mat-option> </mat-select> </mat-form-field> </form>
因此,我正在遍历从 ngOnInit 上的 api 获取的组并推送所选组的 id
组模型看起来像这样 { id: 1, name = "Admin", level: 2, updatedDate : ..., createDate: ...}
组件.ts
public composeGroup: FormGroup;
public groups: Group[];
constructor(
public fb: FormBuilder,
public userService: UserService
){
this.composeGroup = fb.group({
groupIds: [],
sentFrom: null
});
}
ngOnInit(){
this.userService.getGroups().subscribe((res) =>{
this.groups = res;
})
}
selectAllGroups(){
// Need to push all groups into composeGroup.groupIds if Select All option is choosen
// Also need to update the UI checkbox to select all
}