Angular 7 get element id value in component's template side

Viewed 6901

Is it possible to get the value of html element's id value inside a template itself (not .ts side)? Look at this example:

<div class="fillable-area">
  <textarea id='middle_name' required>{{ dataService.getUserField('middle_name') }}</textarea>
  <label for="middle_name">Middle name</label>
</div>

I have an id element which is exactly the same as the name of the getUsetField() parameter of my data service. There is a lot of elements like this, so I think it would be nice to be able to do something like this (just to not repeat myself):

<textarea id='middle_name' required>{{ dataService.getUserField(this.id) }}</textarea>

I need it to be able to loop thru all of my data fields (which come from a database and get stored in objects), get their key names and find corresponding fields in a template.

1 Answers

It can be done with the help of a template reference variable. In the example below, the variable txt is defined for the textarea element, and used to get the id of the element:

<textarea #txt id="middle_name" required>{{ dataService.getUserField(txt.id) }}</textarea>
Related