简体   繁体   中英

Angular 6, How to get the target element for an 'onSelectionChange' dom event?

Using angular 6, whenever the selection changes I want to get the "formControlName" of the corresponding element.

HTML

    <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid">
        <mat-select placeholder="Select Product" formControlName="newProductCode" required>
            <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl)">{{pl.productCode}}</mat-option>
        </mat-select>
        <mat-hint align="start">
            <strong>Select</strong>
        </mat-hint>
    </mat-form-field>

TYPESCRIPT "changeValues"

 changeValues(event, data: ProductListModel) {
      // here i need formControlName
 }

I have tried the following ways but no help:

 changed(event) {
   console.log(event.target.id); 
 }

I have also tried

changed(event) {
 const target = event.target || event.srcElement || event.currentTarget;
 const idAttr = target.attributes.id;
 const value = idAttr.nodeValue;
}

Am i missing something, but why don't you just provide it like this:

 changeValues(event, data: ProductListModel, controlName: string) { // here i need formControlName } 
 <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select placeholder="Select Product" formControlName="newProductCode" required> <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl,'newProductCode')">{{pl.productCode}}</mat-option> </mat-select> <mat-hint align="start"> <strong>Select</strong> </mat-hint> </mat-form-field> 

To get reference to the component itself, you can use:

 changeValues(event, something, matComponent) { // not using material components so i dont know the class } 
 <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select #matSelect placeholder="Select Product" formControlName="newProductCode" required> <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl, matSelect)">{{pl.productCode}}</mat-option> </mat-select> <mat-hint align="start"> <strong>Select</strong> </mat-hint> </mat-form-field> 

Here is used template referencing with #matSelect and then providing it to callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM