注意事项:
单选按钮表单里 fromControlName 和name 的值必须相同
1.导入
import { ReactiveFormsModule } from '@angular/forms'
2.html模板
<form [formGroup]="fg">
<label>性别:</label>
<input type="radio" id="male" name="sex" value='1' formControlName="sex">
<label for="male">男</label>
<input type="radio" id="female" name="sex" value='2' formControlName="sex">
<label for="female">女</label>
<button (click)="run()">跳转</button>
</form>
3. ts文件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
public value:string='2';
constructor() { }
ngOnInit() {
this.backGoup();
}
public fg:FormGroup;
backGoup(){
this.fg=new FormGroup(
{
sex:new FormControl(this.value)
}
);
}
run(){
//TypeScript里的解构形式
//未取出key 为sex的value值
let {sex}=this.fg.value;
console.log(sex);
}
}