我有一个问题,理解为什么在一种情况下Reactive Forms不能按预期工作。
我的模板中有一个带有单选按钮的按钮组,每个输入都嵌套在一个标签中。当我选择一个单选按钮时,FormControl
中相应的FormGroup
没有更新。
当我将输入控件放在标签之外时,一切都按预期工作。
我需要做些什么来使我的例子成功?
以下是代码:
app.component.html:
<div [formGroup]="testForm">
<div class="row">
<div class="col-xs-12">
<div class="btn-group" data-toggle="buttons">
<label class="btn active">
<input type="radio" value="0" name="regularity" formControlName="regularity" checked>
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>1 W</span>
</label>
<label class="btn active">
<input type="radio" value="1" name="regularity" >
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>2 W</span>
</label>
<label class="btn active">
<input type="radio" value="2" name="regularity" >
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>1 M</span>
</label>
<label class="btn active">
<input type="radio" value="3" name="regularity" >
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>3 M</span>
</label>
<label class="btn active">
<input type="radio" value="4" name="regularity" >
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>6 M</span>
</label>
<label class="btn active">
<input type="radio" value="5" name="regularity" >
<i class="fa fa-circle-o fa-2x"></i>
<i class="fa fa-dot-circle-o fa-2x"></i>
<span>1 Y</span>
</label>
</div>
</div>
</div>
</div>
{{testForm.value|json}}
app.component.ts:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private testForm: FormGroup;
constructor(private _fb: FormBuilder) {
this.testForm = _fb.group({
regularity: ''
});
}
title = 'app works!';
}
编辑: 显然使用jQuery存在问题。当我从.angular-cli.json中删除jQuery时,一切正常。
答案 0 :(得分:0)
这可能是您的解决方案为每个控件提供表单控件名称 here you can find some extra stuff
<input type="radio" formControlName="food" value="beef" > Beef
<input type="radio" formControlName="food" value="lamb"> Lamb
<input type="radio" formControlName="food" value="fish"> Fish
答案 1 :(得分:0)
虽然这不是最佳做法,但我做了一个临时解决方法:
<label class="btn active" (click)="setValue('3')>
<input type="radio" value="3" formControlName="regularity">
</label
和打字稿:
import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private testForm: FormGroup;
private regularity: FormControl
ngOnInit(){
this.buttonsPlatform = new FormControl();
this.testForm= new FormGroup({
regularity: this.regularity,
});
}
title = 'app works!';
public setValue(newValue) : void(){
this.regularity.setValue(newValue);
}
}