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

时间:2019-04-26 15:35:17

标签: angular

在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

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

这是我在app.js中显示值的方式:

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

我需要进行哪些更改,以确保如果用户仅单击“发送”,则会将默认值(在这种情况下为“是”)传递到服务器?非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以在其中设置默认值

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