Search code examples
angulartypescriptform-control

How to get the name of FormControl in Typescript


I have two dropdown with multiselect.

<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>

In Typescript I need to know which is the name of FormControl that is clicked because I want to make different things in both cases.

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

Solution

  • You can send the formcontrol name manually from template to your component method

    <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 code:

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

    Alternatively you can observe form control valueChanges for each form control and get its name