如何在 Typescript 中获取 FormControl 的名称

How to get the name of FormControl in Typescript

我有两个多选下拉菜单。

<mat-form-field>
  <mat-select [formControl]="FirstFormControl" multiple>
    <mat-option (onSelectionChange)="selectA($event) *ngFor="let msj of filter?.msj" [value]=msj>{{msj}}
    </mat-option>
  </mat-select>
</mat-form-field>



 <mat-form-field>
      <mat-select [formControl]="SecondFormControl" multiple>
        <mat-option (onSelectionChange)="selectB($event) *ngFor="let guide of filter?.guide" [value]=guide>{{guide}}
        </mat-option>
      </mat-select>
  </mat-form-field>

在 Typescript 中,我需要知道单击的 FormControl 的名称是哪个,因为我想在这两种情况下做不同的事情。

FirstFormControl = new FormControl();
SecondFormControl = new FormControl();

您可以将 formcontrol 名称从模板手动发送到您的组件方法

<mat-form-field>
      <mat-select [formControl]="SecondFormControl" multiple>
        <mat-option (onSelectionChange)="selectB($event, 'SecondFormControl') *ngFor="let guide of filter?.guide" [value]=guide>{{guide}}
        </mat-option>
      </mat-select>
 </mat-form-field>

ts代码:

selectB(event, cntrlName){
  console.log(cntrlName);
  console.log(this.myForm.get(cntrlName).value);
}

或者,您可以观察每个表单控件的表单控件 valueChanges 并获取其名称