无法设置Bootstrap 4单选按钮的初始值

时间:2018-06-04 00:38:23

标签: angular

我在设置单选按钮的初始值时遇到了一些困难。在我的组件中,我创建了表单并在ngOnInit()期间提供了初始值:

this.form = this.formBuilder.group({
  ...,
  showInDirectory: [
    true,
  ],
});

我希望收音机最初设置为true。以下是相关的模板代码:

<div class="custom-control custom-radio">
  <input formControlName="showInDirectory" [value]="true" type="radio" id="directoryTrue" name="showInDirectory" class="custom-control-input">
  <label class="custom-control-label" for="directoryTrue">Yes</label>
</div>
<div class="custom-control custom-radio">
  <input formControlName="showInDirectory" [value]="false" type="radio" id="directoryFalse" name="showInDirectory" class="custom-control-input">
  <label class="custom-control-label" for="directoryFalse">No</label>
</div>

但是&#34; true&#34;无线电从未被初选。我已经尝试使用字符串值为true / false,1/0,它仍然无法按预期工作。我做错了什么?

2 个答案:

答案 0 :(得分:0)

<input type="radio" [checked]="true">

您必须首先使用为其选择的指令。里面可能有任何布尔表达式,如[checked] =&#34; myVar == myOtherVar&#34;来自你的组件。

答案 1 :(得分:0)

我检查你的代码是否接缝工作:

    <div [formGroup]="form">
<div class="custom-control custom-radio">
  <input formControlName="showInDirectory" [value]="true" type="radio" id="directoryTrue" name="showInDirectory" class="custom-control-input">
  <label class="custom-control-label" for="directoryTrue">Yes</label>
</div>
<div class="custom-control custom-radio">
  <input formControlName="showInDirectory" [value]="false" type="radio" id="directoryFalse" name="showInDirectory" class="custom-control-input">
  <label class="custom-control-label" for="directoryFalse">No</label>
</div>
</div>

表单实现:

form:FormGroup;
  constructor(fb:FormBuilder){
    this.form = fb.group({
      showInDirectory: [ true]
    });
  }

example at stackblitz

相关问题