在 Angular 中取消选择垫选定值

Deselect Mat Selected Value in Angular

我正在构建一个应用程序,其中我使用了 Angular 12 和 Angular Material。在这里,我有一个 Material Select 和一个 Reset 按钮。我需要在单击重置按钮时从 Mat Select 中取消选择的值。我尝试了各种方法,例如将 [value] 设置为 null 并使用 Reactive 表单将值设置为 null 或空字符串。但是没用。

为了更好的理解下面的代码文件

alarm.component.html

  <form [formGroup]="dateFormGroup">
    <mat-form-field>
      <mat-label>{{'Filter'| translate}} {{'DATETIME'|translate}}</mat-label>
      <mat-select id="dateTimeSelected" name="dateTimeSelected" formControlName="dateTimeSelected">
        <option value="" disabled>{{'Select'|translate}} {{'DATETIME'|translate}}</option>
        <mat-option *ngFor="let item of dateTimeArr" [value]="item" (click)="dateTimeFilter(item)">
          {{item}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <button mat-flat-button class="btn commonBtn" (click)="resetFilters()">{{'Reset'|translate}}</button>
  </form>

alarm.component.ts

export class AlarmComponent implements OnInit{
dateFormGroup = new FormGroup({});

constructor(){
    this.dateFormGroup =  new FormGroup({
      dateTimeSelected: new FormControl()
    });
  }
  resetFilters(): any {
    console.log(this.dateFormGroup.value.dateTimeSelected);
    this.dateFormGroup.value.dateTimeSelected = null;
    this.dataSource.filter = '';
    this.todoService.getAlerts(this.currentSensorId).subscribe((response: any) => {
      this.tableData = [];
      this.dateTimeArr = [];
      for (let i = 0; i < response.alertResponses.length; i++) {
        this.tableData.push(response.alertResponses[i]);
        this.dateTimeArr.push(moment(response.alertResponses[i].dated).format('YYYY-MM-DD'));
        this.dateTimeArr = [...new Set(this.dateTimeArr)];
      }
    });
  }
}

截图

有什么解决办法吗?

您不能像这样分配值:this.dateFormGroup.value.dateTimeSelected = null

您必须使用 patchValue 或 setValue 来重置控件值。

this.dateFormGroup.controls['dateTimeSelected'].setValue(null);