从 Angular 4 中的选择选项中获取价值 [英] Get Value From Select Option in Angular 4
本文介绍了从 Angular 4 中的选择选项中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 Angular 4 的选择选项中获取值?
我想将它分配给 component.ts 文件中的一个新变量.我试过了,但什么也没输出.
你也可以用 [(ngModel)] 来做吗?
component.html
</表单>
component.ts
HelloCorp() {constcorporationObj =corporation.value;}
解决方案
作为一般(参见 Stackblitz 此处:https://stackblitz.com/edit/angular-gh2rjx):
<块引用>HTML
<块引用>
打字稿
导出类 AppComponent {selectedOption:字符串;打印选项:字符串;选项 = [{名称:选项1",值:1},{ 名称:选项 2",值:2 }]打印() {this.printedOption = this.selectedOption;}}
<小时>
在您的特定情况下,您可以像这样使用 ngModel:
</表单>你好公司(){console.log("我的输入:",corporateObj);}
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);
}
这篇关于从 Angular 4 中的选择选项中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文