0

I have this element having dynamic id as it is inside a loop:

<mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id">
 <mat-option *ngFor="let row of txnTypeList" value="{{row.id}}">{{row.name}}</mat-option>
</mat-select>

I am accessing this element in ts file like this:

document.getElementById('field-' + permissionName + '-txn_type_id');

I am getting the element but there is no value attribute. How can i get the selected values for this element.

I could not find any way to do this task using template ref. variable due to the dynamic ids where id's name consist of string value and variable.

  • 1
    In Angular you get a component using a template reference variable and ViewChild (or ViewChildren), **not** by "id", see the docs, [here](https://angular.io/guide/template-reference-variables) and [here](https://angular.io/api/core/ViewChild) – Eliseo Sep 27 '22 at 10:26
  • Does this answer your question? [Angular mat-checkbox getElementById](https://stackoverflow.com/questions/46832522/angular-mat-checkbox-getelementbyid) – Philipp Kief Sep 27 '22 at 14:10

1 Answers1

0

By importing FormsModule in your module and using [(ngModel)], you could initialize your select contorls and access the values any time without any html reference to controls:

<div *ngFor="let element of elements; let i=index;">
  <mat-select multiple class="dw-input" [(ngModel)]="values[i].txn_type_ids" (selectionChange)="logValues()">
    <mat-option *ngFor="let row of txnTypeList" value="{{row.id}}">{{row.name}}</mat-option>
   </mat-select>
</div>

ts:

values: any[] = [];
elements = [
    {
      name: "name1",
      txn_type_id: "1,2"
    }, 
    {
      name: "name2",
      txn_type_id: "3"
    }
];

constructor() {
    this.elements.forEach(elem => {
      this.values.push({
        "txn_type_ids": elem.txn_type_id ? elem.txn_type_id.split(',') : []
      });
    });
}
logValues() {
    console.log(this.values); 
}

Also you can use ReactiveFormsModule and FormsArray to access form controls: like this.

Mostafa
  • 61
  • 6