[英]Angular2 + binding selected option + ngForm
How can I get the selected item to submit to the service? 如何获取所选项目以提交给服务? Doing like form.value['name'] works for field name, but doesn't for field country. 像form.value ['name']一样适用于字段名称,但不适用于字段国家/地区。
I've tried some solutions I've found with selectedCountry, but I think I didn't understand how to do it so. 我已经尝试过使用selectedCountry找到的一些解决方案,但是我认为我不知道该怎么做。
Considerations: 注意事项:
signup.component.html signup.component.html
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div class="input-field">
<input type="text" id="name" name="name" class="validate" ngModel>
<label for="name" data-error="nome inválido">Nome</label>
</div>
<div class="input-field">
<select id="country" name="country" [(ngModel)]="selectedCountry">
<option [ngValue]="" selected>Escolha um país</option>
<option *ngFor="let country of countries" [ngValue]="country" > {{country.code}} - {{country.name}} </option>
</select>
<label for="country">País onde reside</label>
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
signup.component.ts signup.component.ts
export class SignupComponent implements OnInit {
countries: any[];
selectedCountry: Object = {};
onSubmit(form: NgForm) {
this.authService
.signUp(form.value['name'], form.value['country'])
.subscribe(signUpResult => {
//some code
});
}
}
Please try the Following Way 请尝试以下方式
@Component({
selector: 'my-app',
template:`
<h1>Selecting Number</h1>
<select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()">
<option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
</select>
{{levelNum}}
`,
})
export class AppComponent {
levelNum:number;
levels:Array<Object> = [
{num: 0, name: "AA"},
{num: 1, name: "BB"}
];
toNumber(){
this.levelNum = +this.levelNum;
console.log(this.levelNum);
}
}
app.module.ts app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
// .. some other components
],
imports: [ // import Angular's modules
BrowserModule,
FormsModule
// .. some other modules
],
providers: []
})
export class AppModule {}
your.component.ts your.component.ts
@Component({
selector: 'my-app',
template:`
<select id="country" name="country" [(ngModel)]="selectedCountry">
<option value="">Escolha um país</option>
<option *ngFor="let country of countries" [ngValue]="country" > {{country.code}} - {{country.name}} </option>
</select>
`,
})
export class AppComponent {
public selectedCountry;
}
Edited 已编辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.