【问题标题】:Select All Option in Angular 6+在Angular 6+中选择所有选项
【发布时间】: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

【问题讨论】:

  • 在做任何事情之前,选择使用响应式表单或模板驱动表单,它们不能一起使用。

标签: angular mat-form-field


【解决方案1】:

怎么样

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

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

【讨论】:

  • 似乎不起作用。当我单击 selectAllGroups() 选项时,该按钮未检查。我认为这与this.groups的结构有关。在原始帖子中,我说 { id: 1, name = "Admin", level: 2, updatedDate : ..., createDate: ...}。我的错。它是 [{ id: 1, name = "Admin", level: 2, updatedDate : ..., createDate: ...}, { id: 2, name = "User", level: 2, updatedDate : .. ., createDate: ...},..]。不知道是不是这个问题。
  • 终于让它工作了。 selectAllGroups(){ 让 groupsValues = []; for(let group of this.groups){ groupsValues.push(group.id) } this.composeGroup.patchValue({groupIds: groupValues}); }。谢谢你:-)
【解决方案2】:

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

selectAllGroups(){
    this.composeGroup.patchValue({ groupIds: this.groups?.map(x => x.id) });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2020-10-26
    • 2018-12-21
    • 2020-05-29
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多