raj m
raj m

Reputation: 2023

How to implement radio box in angular2 rc5

Can anybody please suggest me to implement the radio button. I have two radio AM and PM. First time AM should be checked. And whenever user clicks the button value should be updated in controller object.

time;
time = {am:"yes",pm:"no"};

Upvotes: 0

Views: 105

Answers (3)

raj m
raj m

Reputation: 2023

 <input type="radio" [(ngModel)]="step1Data.addInfoProvided" name="addInfoLinks" class="radio-box" value="Yes" id="yes" 
                                />
                                <label class="radio-caption lang-yes"    for="yes"></label>
                                <input type="radio"       [(ngModel)]="step1Data.addInfoProvided" name="addInfoLinks" class="radio-box" value="No" id="no" 
                                />
                                <label class="radio-caption lang-no" for="no"></label>

Upvotes: 0

slaesh
slaesh

Reputation: 16917

Best way would be to use [(ngModel)].

But it will not generate that object you described, but see in action: https://plnkr.co/edit/ojRw5lrXGONkKQ7yroKW?p=preview

You can simply form your object like this:

let timeObj = {
   am: time === 'am',
   pm: time === 'pm',
};
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule} from '@angular/forms'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="print()">Hello {{name}}</h2>

      <input type="radio" name="radiobuttongroup1" value="am" [(ngModel)]="time" >
      <label> AM</label><br>

      <input type="radio" name="radiobuttongroup1" value="pm" [(ngModel)]="time" >
      <label> PM</label>

    </div>
  `,
})
export class App {

  time = 'am';

  name:string;
  constructor() {
    this.name = 'Angular2'
  }

  print() {
    console.log(this.time);
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Upvotes: 1

Sanket
Sanket

Reputation: 20037

Try like this-

html template:

<div class="form-group">
    <div>
        <label class="radio_option">
        <input type="radio" class="option-input radio" value="am" id="am" name="time" checked />
        <span (click)="disabledstatus && changeDisabledStatus(!disabledstatus)"></span>
        </label>
        <label id="radiolabel">AM</label>
    </div>
    <div>
        <label class="radio_option">
        <input type="radio" class="option-input radio" value="pm" id="pm" name="time">
        <span (click)="!disabledstatus && changeDisabledStatus(disabledstatus)"></span>
        </label>
        <label id="radiolabel">PM</label>
    </div>
</div>

In your component-

export class SomeComponent implements OnInit {

    disabledstatus = false;

    constructor( ) { }

    ngOnInit() { }

    changeDisabledStatus() {    
        this.disabledstatus = !this.disabledstatus;
    }

}

See if this helps.

Upvotes: 1

Related Questions