如何在 ngOnInit() 中设置单选按钮 FormControl 的默认值



在我的 Angular 应用程序中,我正在尝试设置单选按钮组的默认值,如下所示:

TS:

ngOnInit() {
this.conditionsForm = this.fb.group({
reportInjury: new FormControl('Yes', Validators.required),         
});

.HTML:

<radio-button-wrapper formControlName="reportInjury" name="reportInjury">
<radio heading="Yes" value="Yes" cid="reportInjuryYes"
name="reportInjuryYes">
</radio>
<radio heading="No" value="No" cid="reportInjuryNo" name="reportInjuryNo">
</radio>
</radio-button-wrapper>

页面加载时,默认情况下选择"是"单选按钮,但是如果我将表单发送到 Node.js 服务器而不触摸单选按钮并将单选按钮内容打印到控制台,则会显示undefined

但是,如果我选择">"单选按钮,然后重新选择"是"单选按钮,则">"将打印在控制台上。

以下是我在应用程序中显示值的方式.js:

${content['formBody']['damageDetailsTwo']['damageReported'].value}

我需要进行哪些更改才能确保如果用户只是单击"发送",则将默认值(在本例中为"是")传递给服务器?多谢!

您可以在

registrationForm = this.fb.group({
reportInjury: ['yes', [Validators.required]]
})

在 HTML 中

<div class="custom-control custom-radio">
<input id="yes" type="radio" class="custom-control-input" value="yes" name="reportInjury" formControlName="reportInjury">
<label class="custom-control-label" for="yes">Yes</label>
</div>
<div class="custom-control custom-radio">
<input id="no" type="radio" class="custom-control-input" value="no" name="reportInjury" formControlName="reportInjury">
<label class="custom-control-label" for="no">No</label>
</div>

演示 https://stackblitz.com/edit/angular-radio-buttons-default

最新更新