After struggling to find a solution for retrieving the text of a selected item from a dropdown, I decided to create a common directive. This directive would allow me to easily access the text for all dropdown items when used in my code. Below is the snippet of my implementation:
app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div>
<p>Text from directive: {{selectedText}} </p>
<p>Data from Parent Component - {{selectedProp}}</p>
<select [psSelectText]="'selectedText'" name="selectedProp" [(ngModel)]="selectedProp" >
<option value=""></option>
<option *ngFor="let i of arrayList" value="{{i.value}}">{{i.text}}</option>
</select>
</div>
<br>
<button (click)="hitMe()">Hit me</button>
Custom Directive:
import { Directive, ElementRef, HostListener, Input, SimpleChanges, OnChanges, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { NgModel } from '@angular/forms';
import { SelectText } from './select-text.model';
@Directive({
selector: '[ngModel][psSelectText]',
providers: [NgModel],
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PsSelectText implements OnChanges {
@Input('psSelectText') selectedText: string;
@Input('ngModel') selectedModel: NgModel;
constructor(private el: ElementRef, public model: NgModel, private viewContainerRef: ViewContainerRef) { }
ngOnChanges(changes: SimpleChanges) {
console.log(this.el)
if (changes.selectedModel) {
// this.selectedText.valueAccessor.writeValue(changes.selectedModel.currentValue);
setTimeout(() => {
this.viewContainerRef['_view'].component[this.selectedText] =
this.el.nativeElement.selectedOptions[0].text;
}, 0);
}
}
onInputChange(event) {
// Only get selected change
}
}
Initially, I achieved this by passing a single variable like
[psSelectText]="'selectedText'",
However, I now aim to pass an object property such as selectedText2.text. Here, I want the text of the dropdown item to be set to the selectedText2.text property within the directive.
In order to achieve this, I plan to pass the attribute in the following manner:
[psSelectText]="selectedText2.text"
Subsequently, I intend to set the text of the dropdown using this field selectedText2.text
Is there a way to accomplish this? Thank you for your assistance.
Specifically, the modification required here is shown below:
// The property "this.selectedText2.text" will be dynamically provided,
this.viewContainerRef['_view'].component[this.selectedText2.text] =
this.el.nativeElement.selectedOptions[0].text;
Demo: https://stackblitz.com/edit/angular-dropdown-selected-text