gpt4 book ai didi

angular-material2 - 选择所有垫选项并取消选择所有

转载 作者:行者123 更新时间:2023-12-04 05:16:09 25 4
gpt4 key购买 nike

我有如下场景:

enter image description here

我要实现的是:

  • 当用户点击 全部 然后应选择所有选项,当用户单击 时全部 再次,所有选项都将被取消。
  • 全部 选项被选中,用户单击除 All 之外的任何其他复选框然后 全部 并单击复选框应取消选择。
  • 当用户一一选择 4 个选项时,则应选择 All。

  • HTML文件
    <mat-select placeholder="User Type" formControlName="UserType" multiple>
    <mat-option *ngFor="let filters of userTypeFilters" [value]="filters.key">
    {{filters.value}}
    </mat-option>
    <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
    </mat-select>

    TS文件
    this.searchUserForm = this.fb.group({
    userType: new FormControl('')
    });

    userTypeFilters = [
    {
    key: 1, value: 'Value 1',
    },
    {
    key: 2, value: 'Value 2',
    },
    {
    key: 3, value: 'Value 3',
    },
    {
    key: 4, value: 'Value 4',
    }
    ]

    toggleAllSelection() {
    if (this.allSelected.selected) {
    this.searchUserForm.controls.userType
    .patchValue([...this.userTypeFilters.map(item => item.key), 0]);
    } else {
    this.searchUserForm.controls.userType.patchValue([]);
    }
    }

    现在,如何实现 第二点和第三点

    Stackblitz 是: https://stackblitz.com/edit/angular-material-with-angular-v5-znfehg?file=app/app.component.html

    最佳答案

    使用如下代码创建函数点击每个 mat-optionselect()/deselect()所有选项:

    见堆栈 Blitz :https://stackblitz.com/edit/angular-material-with-angular-v5-jsgvx6?file=app/app.component.html

    TS:

    tosslePerOne(all){ 
    if (this.allSelected.selected) {
    this.allSelected.deselect();
    return false;
    }
    if(this.searchUserForm.controls.userType.value.length==this.userTypeFilters.length)
    this.allSelected.select();

    }
    toggleAllSelection() {
    if (this.allSelected.selected) {
    this.searchUserForm.controls.userType
    .patchValue([...this.userTypeFilters.map(item => item.key), 0]);
    } else {
    this.searchUserForm.controls.userType.patchValue([]);
    }
    }

    HTML:
    <form [formGroup]="searchUserForm" fxFlex fxLayout="column" autocomplete="off" style="margin: 30px">
    <mat-select placeholder="User Type" formControlName="userType" multiple>
    <mat-option *ngFor="let filters of userTypeFilters" [value]="filters.key" (click)="tosslePerOne(allSelected.viewValue)">
    {{filters.value}}
    </mat-option>
    <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
    </mat-select>
    </form>

    关于angular-material2 - 选择所有垫选项并取消选择所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51580095/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com