2

I have a form in angular (v2.4.8) which uses ngFor in a radio selection based on the example in scotch.io. This doesn't work in my application, if I click on a radio the user.category does not get updated.

Code for compoonent:

export class RegistrationComponent implements OnInit {

  public user: User;

  public userTypes = [
    {value: 'type1', display: 'Type 1'},
    {value: 'type2', display: 'Type 2'},
    {value: 'type3', display: 'Type 3'}
  ];

  constructor() { }

  ngOnInit() {
    this.user = {
      name: '',
      email: '',
      category: this.userTypes[0].value
    }
  }

  public save(isValid: boolean, f: User) {
    console.log(f);
  }

}

And the template:

<div class="btn-group" data-toggle="buttons">
  <label *ngFor="let userType of userTypes" class="btn btn-outline-secondary">
    <input type="radio" name="category" [(ngModel)]="user.category" [value]="userType.value"> {{userType.display}}
  </label>
</div>

The user interface is as follows:

export interface User {
  name: string;
  email: string;
  category: string;
}

Edit

This appears to be an issue with using bootstrap btn-group with angular, looks like the click event i handled correctly. I fixed it by adding a click event to the label. Answer below.

3
  • are you getting any errors? also any particular reason for doing *ngFor on a label? Commented Mar 13, 2017 at 14:48
  • 2
    your code if works fine to me, just verify that you imprted FormsModule in your module. Commented Mar 13, 2017 at 14:53
  • @BougarfaouiElhoucine the issues seems to be with bootstrap rather than angular. Commented Mar 13, 2017 at 15:04

1 Answer 1

4

This is an issue with bootstrap btn-group radios rather than angular. Workaround is to add a click event to the label.

HTML:

<label *ngFor="let userType of userTypes" class="btn btn-outline-secondary" (click)="changeCategory(userType.value)">
  <input type="radio" name="category" [(ngModel)]="user.category" [value]="userType.value"> {{userType.display}} 
</label>

Javascript - added to component:

public changeCategory(category) {
  this.user.category = category;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.