【问题标题】:Set form control holding multple selection in mat select to null将在 mat select 中保持多重选择的表单控件设置为 null
【发布时间】:2021-11-16 22:06:35
【问题描述】:

配合选择具有多选功能。如何将持有这些多项选择的表单控件值设置为空......在我的情况下它不起作用......

reset(){
    this.form.reset();
    return false
    }

this.form = this.formBuilder.group({
      category: [''],
});

在模板中

<mat-form-field appearance="outline">
                        <mat-label>Categories</mat-label>
                        <mat-select formControlName="category" multiple>
                          <mat-select-trigger>
                        <mat-icon matPrefix *ngIf="f['category'].value" (click)="clearCategory($event)"
                         class="icon" title="clear">clear</mat-icon>
                            {{f['category'].value ? f['category'].value[0] : ''}}
                            <span *ngIf="f['category'].value?.length > 1" class="example-additional-selection">
                              (+{{f['category'].value.length - 1}} {{f['category'].value?.length === 2 ? 'other' : 'others'}})
                            </span>
                          </mat-select-trigger>
                          <mat-option #allSelectedCategories (click)="toggleAllCategories()" [value]="0" >
                              All Categories (default)
                          </mat-option>
                          <mat-option *ngFor="let category of categories" 
                          (click)="toggleOnCategory(allSelectedCategories.viewValue)"
                          [value]="category">{{category}}</mat-option>
                        </mat-select>
                      </mat-form-field> 

单击重置按钮时,类别的值不会从表单值中清除,而只能从输入字段中清除

 <button type="reset" mat-raised-button (click)="reset()" 
                      style="margin-right: 5px;">
                        Reset
                    </button>

【问题讨论】:

    标签: angular typescript angular-material multipleselection mat-select


    【解决方案1】:

    您希望该按钮清除所有多选复选框吗?换句话说,用户检查了一些然后你想将它们重置为未选中?

    试试这个:

    selectedOptions = [];

    更新:很抱歉,您需要类似的东西:

    <mat-selection-list [(ngModel)]="selectedOptions" [compareWith]="compareFunction">
    

    【讨论】:

      【解决方案2】:

      .reset() 不会清除表单控件中的值。 It resets the values of the controls to what they were before changes were made。这在 Angular(在所有变体中,例如 FormControl.reset()NgForm.resetForm() 等)和纯 JavaScript 中的工作方式相同。

      【讨论】:

        猜你喜欢
        • 2019-12-11
        • 1970-01-01
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 2019-01-03
        • 2020-10-08
        • 2021-06-17
        • 1970-01-01
        相关资源
        最近更新 更多