如何在无效形式中设置Prime NG单选按钮默认值

时间:2018-02-19 17:51:36

标签: angular primeng

下面是我的代码,我需要将默认值传递给单选按钮

<div class="ui-g-12">
    <p-radioButton name="group1" value="Option 1" label="Option 1" [(ngModel)]="val1" inputId="opt1"></p-radioButton>
</div>
<div class="ui-g-12">
    <p-radioButton name="group1" value="Option 2" label="Option 2" [(ngModel)]="val1" inputId="opt2"></p-radioButton>
</div>
<div class="ui-g-12">
    <p-radioButton name="group1" value="Option 3" label="Option 3" [(ngModel)]="val1" inputId="opt3"></p-radioButton>
</div>

任何人都可以解释如何在表单加载时将默认值设置为单选按钮

2 个答案:

答案 0 :(得分:7)

首先将您的表单构建方式更改为ReactiveForms方式:

<form [formGroup]="myForm">
  <div class="ui-g-12">
    <p-radioButton name="group1" value="Option 1" label="Option 1" formControlName="myRadio" inputId="opt1"></p-radioButton>
  </div>
  <div class="ui-g-12">
    <p-radioButton name="group1" value="Option 2" label="Option 2"  formControlName="myRadio"  inputId="opt2"></p-radioButton>
  </div>
  <div class="ui-g-12">
      <p-radioButton name="group1" value="Option 3" label="Option 3"  formControlName="myRadio"  inputId="opt3"></p-radioButton>
  </div>
</form>

在组件中,在初始化时设置默认值:

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  myForm;
  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      myRadio: ['Option 1', []] // This set default value
    })
  }
}

运行示例:https://stackblitz.com/edit/angular-fu81jc

Primeng docs:https://www.primefaces.org/primeng/#/radiobutton

ReactiveForms docs:https://angular.io/guide/reactive-forms

答案 1 :(得分:0)

除了@Ruben 之外,对于 Primeng 中的布尔类型,您可以在 p-radioButton 中使用 [value] = true。