如何使用反应形式以角度验证单选按钮字段

时间:2020-03-06 05:26:26

标签: javascript angular ionic-framework

我有名称和值,要从ts端调用并想对其进行验证。这些值不是从事件中获取的,并且它一直在发送,例如(on)。

<form [formGroup]="reactiveForm">
  <div *ngFor="let item of checkBoxValueList">
    <input 
    type="radio" 
    formControlName="yourChoice"
    [value]="item"
    (change)="event($event)"
    >
    {{item}}
  </div>
 </form>
 <pre>
 {{reactiveForm.value | json}}
</pre>
   checkBoxValueList = [
    'Reading',
    'Watching',
    'Traveling',
    'Cooking'
  ];
  reactiveForm: FormGroup = new FormGroup({
    yourChoice: new FormControl()
  });

  constructor() {}

  edit(eve) {
    console.log(eve);
    console.log("target", eve.target.value);
  }

2 个答案:

答案 0 :(得分:2)

您可以直接传递您的值而不是事件。 试试吧。

(change)="edit(item)".

希望这会有所帮助。

答案 1 :(得分:2)

我猜您只需要在更改事件上选择选定的值并对其进行验证。因此,您可以在此处通过我们的reactForm变量访问单选按钮的选定值。

event(eve) {
 console.log(eve);
 // console.log("target", eve.target.value);
 console.log(this.reactiveForm.value['yourChoice']); //this will give your selected value
}

希望这会有所帮助!