[Angular2 Form] Create Radio Buttons for Angular 2 Forms

Using Radio Buttons in Angular 2 requires a basic understanding of forms as well as how their labels will match up with each input. This lesson shows how to use *ngFor with radio buttons and covers the quirks of the id property and forattributes as well as how to style validation of radio buttons.

 

  <!-- Radio button-->
  <form action="" name="myFom4" #myForm4="ngForm">
    <div *ngFor="let location of locations">
      <input type="radio"
             name="location"
             ngModel
             [value]="location"
             [id]="location"
             required
      >
      <label [attr.for]="location">{{location}}</label>
    </div>
  </form>
  <pre>
    {{myForm4.value | json}}
  </pre>

 

input.ng-invalid + label:after {
  content: '<--Requried to selet one'
}

 

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {

  locations: Array<string>;

  constructor() {
  }

  ngOnInit() {
    this.locations = [
      'China',
      'Finland',
      'Norway',
      'Japan'
    ];
  }
}

 

Github

posted @ 2016-09-29 00:57  Zhentiw  阅读(562)  评论(0)    收藏  举报