【发布时间】:2021-05-28 15:26:32
【问题描述】:
我在 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
}
component.ts
【问题讨论】:
-
在做任何事情之前,选择使用响应式表单或模板驱动表单,它们不能一起使用。