How do I get the value from the select option in Angular 4?
I want to assign it to a new variable in the component.ts file. I've tried this but outputs nothing.
Can you also do it using [(ngModel)]?
component.html
<form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm">
<div class="select">
<select class="form-control col-lg-8" #corporation required>
<option *ngFor="let corporation of corporations" [value]="corporationObj">{{corporation.corp_name}}</option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
component.ts
HelloCorp() {
const corporationObj = corporation.value;
}
As a general (see Stackblitz here: https://stackblitz.com/edit/angular-gh2rjx):
HTML
<select [(ngModel)]="selectedOption">
<option *ngFor="let o of options">
{{o.name}}
</option>
</select>
<button (click)="print()">Click me</button>
<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>
Typescript
export class AppComponent {
selectedOption: string;
printedOption: string;
options = [
{ name: "option1", value: 1 },
{ name: "option2", value: 2 }
]
print() {
this.printedOption = this.selectedOption;
}
}
In your specific case you can use ngModel like this:
<form class="form-inline" (ngSubmit)="HelloCorp()">
<div class="select">
<select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
<option *ngFor="let corporation of corporations"></option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
HelloCorp() {
console.log("My input: ", corporationObj);
}