Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Radio Button not Initializing Correctly with Reactive Form

I am starting with Angular 2 and am currently using version 2.2.2

I am writing a reactive form, but I am not able to initialize the selected radio button. The page should load with a radio button selected, but this is not occurring.

I have been unable to locate the source of the problem. From code samples on the Web, I think this should be working. Here is a snippet of my code.

<form [formGroup]="consultaSolicitudesINETELForm"  (ngSubmit)="consulta(consultaSolicitudesINETELForm)">
<input type="radio" formControlName="criterio" value="1"  />
<input type="radio" formControlName="criterio" value="2"  />
<input type="radio" formControlName="criterio" value="3"  />
<input type="text" formControlName="folio" placeholder="folio" required>
 </form>

for the component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
moduleId: module.id,
selector: 'my',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class My implements OnInit {

myForm: FormGroup;

constructor(private fb: FormBuilder) {

}

ngOnInit(): void {
  this.buildForm();
}

buildForm(): void {

  this.consultaSolicitudesINETELForm = this.fb.group({
    criterio: ["2"],
    folio: ["TEST"],

  });

  this.myForm.valueChanges.subscribe(data => this.onValueChanged(data));
  this.onValueChanged();

}

EDIT: Here is a plnkr I forked from an example where I added radio that does not run in my environment. The only difference I see there are version numbers.

EDIT2: OK, I found it has something to do with ng-bootstrap. If I use NgbModule.forRoot() then the radio buttons are not initialized and don't work as expected, if I disable ng-bootstrap then they work, but as I use ng-bootstrap elsewhere I can't do that.

I went around it by using ng-bootstrap's own radio button group and re-designing the web page. I had the radio buttons placed inside a legend of various fieldsets and all content always visible. Now the radios work kind of like tabs, displaying a different div depending on the current selection.

The original purpouse of the radio buttons was to select a working fieldset where all it's elements would be enabled and all others fieldsets' content disabled.

like image 327
dabicho Avatar asked Nov 08 '22 05:11

dabicho


1 Answers

This issue is with ng-bootstrap and is tracked at https://github.com/ng-bootstrap/ng-bootstrap/issues/1125

It's high priority for them.

like image 61
Ron Newcomb Avatar answered Nov 15 '22 07:11

Ron Newcomb