我在 Angular 7 中使用一个 HTML 模板,它由许多单选按钮组成,每个单选按钮都有一个相关联的标签——这与一个 FormGroup 对象相关联。单击标签应更改要选择的单选按钮的状态并更新关联的 FormControl 的值。这行得通,我遇到的问题是设置一个特定的单选按钮以在加载 UI 时选择,或者使用 patchValue
- 加载模板时 formGroup 的状态是正确的,但 UI 不正确反射(reflect)已选择特定的单选按钮。
这是显示问题的代码:
export class AppComponent {
frequencyMinutesOptions: number[] = [1, 2, 5, 10, 60];
myForm: FormGroup;
constructor() {
}
ngOnInit() {
this.myForm = new FormGroup({
frequencyMinutes: new FormControl(5,[])
});
this.myForm.patchValue({'frequencyMinutes':10})
}
}
HTML 模板:
<form [formGroup]="myForm">
<ul>
<li *ngFor="let frequency of frequencyMinutesOptions">
<input id="asset-frequency-{{frequency}}" type="radio" value={{frequency}} formControlName="frequencyMinutes" />
<label for="asset-frequency-{{frequency}}"> {{frequency}} </label>
</li>
</ul>
</form>
相关 CSS:
input {
display: none;
}
input:checked+label {
background-color: blue;
color: #ffffff;
}
您可以在这里看到一个有效的演示:
https://stackblitz.com/edit/angular-of2ubt
(我知道我应该在 Stackoverflow 编辑器中嵌入代码示例,但我不确定如何使用 Angular 7/typescript 或者如果可能的话)
最佳答案
这是一个类型错误。在您的 html 表单中,value="10"被解释为字符串“10”。
你必须使用
this.myForm.patchValue({'frequencyMinutes':'10'})
或(参见 [value])
<input id="asset-frequency-{{frequency}}" type="radio" [value]="frequency" formControlName="frequencyMinutes" />
关于css - Angular 7 : patching value of radio button Form Control does not update UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54214939/