We could create a two way binding and save the "selected" value option to a variable. Because this is a regular html select we use [(ngModel)]
for two way binding.
Also, we also normally use camelCase for property names when using javascript title.Text
-> title.text
, myselect
-> mySelect
, title.Value
-> title.value
etc.
We can then access the variable selected
for processing on (click)
event which triggers function onSave()
click in typescript part of the code.
I use ?
when accessing property to conditionally check the prop exists first, this is just in case.
I use parseInt()
to turn cus_id
coming from template as string, back to a number.
If you don't plan on overwriting the variable prefer const
over let
.
Avoid any
type e:any
-> e: Event
if possible (though not needed in my example).
If possible always prefer strong typing with interface
or class
, it will help you in the long run, that's the beauty of typescript - we strong type stuff.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
selected: string;
titleArray: Title[] = [
{ cus_id: 1, text: 'Hancook', value: '123' },
{ cus_id: 2, text: 'I am legend', value: '456' },
{ cus_id: 3, text: 'Amber the turd', value: '789' },
];
onSave() {
console.log('now saving: ', this.selected);
const arrayItem = this.titleArray.find((item) => item.cus_id === parseInt(this.selected));
window.alert(JSON.stringify(arrayItem));
}
}
export interface Title {
cus_id: number;
text: string;
value: string;
}
Html
<select #myselect [(ngModel)]="selected">
<option *ngFor="let title of titleArray" [value]="title?.cus_id">
{{ title?.text }}
</option>
</select>
<br />
<br />
<button (click)="onSave()">Save data</button>
This could be further simplified instead of using [value]="title?.cus_id"
we could do [value]="title"
and pass the obj title
to variable selected
, then we wouldn't have to search it from titleArray[]
nor interpolate strings to number using parseInt()
- but that's up to you.
Working example: https://stackblitz.com/edit/angular5-select-option-dropdown-qt4yvp?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Findex.html
Welcome to SO, nicely formatted question.