1

我在 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
}

组件.ts

4

2 回答 2

0

我同意对初始帖子的评论 - 删除 ngModel(或不使用 formControl)。至于这个问题,下面的答案几乎是正确的——因为你的 mat-options 中的值是 id,所以用 patchValue 设置的值必须是一个 id 列表(而不是完整的对象)。这应该工作,仍然在一条线上:

selectAllGroups(){
    this.composeGroup.patchValue({ groupIds: this.groups?.map(x => x.id) });
}
于 2021-06-02T22:12:36.257 回答
0

怎么样

selectAllGroups(){
    this.composeGroup.patchValue({ groupIds: this.groups });
}

? https://angular.io/api/forms/FormGroup#patchValue

于 2021-05-28T15:46:04.280 回答