我正在使用FormControl
和FormGroup
伪指令保存表单,但是当我声明该对象时,它在<select>
上没有设置任何值
这是我的组成部分
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-new-user',
templateUrl: './new-user.component.html',
styleUrls: []
})
export class NewUserComponent implements OnInit {
data: FormGroup;
}
ngOnInit(){
this.data = new FormGroup({
name: new FormControl(null, Validators.required ),
city: new FormControl( null, Validators.required )
})
}
sendData() {
console.log( this.data.value );
}
这是我的HTML
<form (ngSubmit)="sendData()" [formGroup]="data">
<input formControlName="name" name="name" type="text" placeholder="name">
<select formControlName="city" name="city">
<option selected disabled>Select a city</option>
<option value="1">Russia</option>
<option value="2">Spain</option>
</select>
</form>
逻辑工作正常,但是重新加载页面时,选择完全没有价值,它是空白(甚至没有“选择城市”),我该如何解决呢?
我尝试了
city: new FormControl()
仍然有错误
答案 0 :(得分:1)
您应该在要选择的默认项中添加属性[value]=null
。
<select formControlName="city" name="city">
<option selected disabled [value]="null">Select a city</option>
<option value="1">Russia</option>
<option value="2">Spain</option>
</select>
答案 1 :(得分:0)
尝试
<select formControlName="city" name="city">
<option [value]="null" disabled>Select a city</option>
<option [value]="1">Russia</option>
<option [value]="2">Spain</option>
</select>
https://stackblitz.com/edit/angular-bv2ueg?file=src%2Fapp%2Fapp.component.html