【发布时间】:2023-03-03 03:50:01
【问题描述】:
我在让单选按钮以我的反应形式正常工作时遇到问题。这是我的组件代码:
export class SettingsFormComponent implements OnInit {
public sForm: FormGroup;
public submitted: boolean;
diagramSettings: DiagramSettings;
constructor(private _formBuilder: FormBuilder, private _settingsService: SettingsService) {
this._settingsService.diagramSettingsSubject.subscribe((dSettings: DiagramSettings) => {
this.diagramSettings = dSettings;
});
this.sForm = new FormGroup({
hoverDelay: new FormControl('', [<any>Validators.required, CustomValidators.range([500, 2000])]),
hoverAction: new FormControl('', []),
leftClickAction: new FormControl('', []),
rightClickAction: new FormControl('',[])
});
this.sForm.setValue({
hoverDelay: this.diagramSettings.hoverDelay,
hoverAction: this.diagramSettings.OnHover,
leftClickAction: this.diagramSettings.OnLeftClick,
rightClickAction: this.diagramSettings.OnRightClick
});
//this.sForm = new FormGroup({
// hoverDelay: new FormControl(500, [<any>Validators.required, <any>Validators.minLength(3)])
//});
}
ngOnInit() {
}
save() {
this.submitted = true; // set form submit to true
this._settingsService.setOpen(false);
// check if model is valid
// if valid, call API to save customer
console.log('in model save. ');
}
}
这是包含表单的模板的一部分:
<form [formGroup]="sForm" novalidate (ngSubmit)="save()">
<div class="form-group" [class.has-error]="!sForm.controls.hoverDelay.valid">
<label class="col-sm-2 control-label" for="hoverDelay">Hover Delay (millilseconds):</label>
<div class="col-sm-10">
<input formControlName="hoverDelay" id="hoverDelay" type="text" class="form-control">
</div>
<span [hidden]="sForm.controls.hoverDelay.valid" [class.help-block]="!sForm.controls.hoverDelay.valid">
HoverDelay is required and needs to be between 500 - 2000
</span>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="hoverActionGroup">On Hover:</label>
<div class="btn-group" id="hoverActionGroup" data-toggle="buttons">
<label class="btn btn-primary" [class.active]="sForm.value.hoverAction === 1">
<input type="radio" name="hoverAction" value="1" formControlName="hoverAction" />Modal
</label>
<label class="btn btn-primary" [class.active]="sForm.value.hoverAction === 2">
<input type="radio" name="hoverAction" value="2" formControlName="hoverAction" />Navigate
</label>
<label class="btn btn-primary" [class.active]="sForm.value.hoverAction === 0">
<input type="radio" name="hoverAction" value="0" formControlName="hoverAction" />Do Nothing
</label>
</div>
</div>
UI 单选按钮似乎可以工作,当您在它们之间切换时,只有一个被选中等。问题是它似乎没有绑定到我的 hoverAction formControl,因为该值始终为 ===0(其中是它被初始化的值)。 hoverDelay 文本输入被绑定到表单控件并进行了适当的更新,所以我必须用单选按钮做一些事情。
如何使用带有 angular2 反应形式的单选按钮?
【问题讨论】:
-
你能在 plunker 中重现这个问题吗?我无法用您的代码自己重现您的问题:)