I am currently working with the MEAN stack (Angular 6) and exploring different methods to build a custom and reusable <select>
form control that utilizes an array of strings fetched from the backend server to generate all the <option>
tags. For instance, let's consider having 3 materials: wood
, metal
, and plastic
. The returned array can be structured in two ways as shown below:
(in my example.component.ts)
form = new FormGroup({
'material' = new FormControl('')
});
get material() {return this.form.get('material');}
materials = [
{
key: "mat_wood",
value: "Wood"
},
{
key: "mat_metal",
value: "Metal"
},
{
key: "mat_plastic",
value: "Plastic"
}
]
or
(in my example.component.ts)
form = new FormGroup({
'material' = new FormControl('')
});
get material() {return this.form.get('material');}
materials = [
{"mat_wood": "Wood"},
{"mat_metal": "Metal"},
{"mat_plastic": "Plastic"}
]
Now, we need to implement this structure in our HTML code which will look like this:
(in my example.component.html)
<form [formGroup]="form">
<div class="select-wrap">
<span class="select-value">{{}}</span>
<select formControlName="material">
<option *ngFor="let mat of materials" value="{{}}">{{}}</option>
</select>
</div>
</form>
The expected output should be:
<select formControlName="material">
<option value="mat_wood">Wood</option>
<option value="mat_metal">Metal</option>
<option value="mat_plastic">Plastic</option>
</select>
This is a typical example of a custom select structure where the selected option text is displayed in the
<span class="select-value">
. The <select>
tag has an opacity set to 0 and positioned over the <span>
, enabling users to click on it to activate.
To achieve the desired functionality, each option must have the corresponding key
prefixed with mat_
inside the value
attribute and display the readable value as text within the option element.
My question is: What is the best way to insert the selected option text into the <span>
element? I am seeking a reusable approach to accomplish this task.
EDIT:
After reviewing the initial response, I realize the usage of a template variable can address the issue. However, if there are multiple dynamically generated selects within an *ngFor loop, is it feasible to have dynamically created template variables for each?