如何让所选项目提交给服务?像form.value ['name']一样适用于字段名称,但不适用于字段国家。
我已经尝试了一些我在selectedCountry中找到的解决方案,但我想我不明白该怎么做。
注意事项:
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
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
});
}
}
答案 0 :(得分:0)
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
@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;
}
被修改
答案 1 :(得分:0)
请尝试以下方式
@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);
}
}