如何在angular2 rc5中实现单选框

时间:2016-09-23 05:50:30

标签: angular radio-button

有人可以建议我实施单选按钮。我有两台收音机AM和PM。应该首先检查AM。每当用户点击按钮值时,应在控制器对象中更新。

<script>
var now = new Date();
var hrs = now.getHours(); //getHours takes visitors local time, not server time.

var msg = "";

if (hrs >  0) msg = "Mornin' Sunshine!"; // REALLY early
if (hrs >  6) msg = "Good morning";      // After 6am
if (hrs > 12) msg = "Good afternoon";    // After 12pm
if (hrs > 17) msg = "Good evening";      // After 5pm
if (hrs > 22) msg = "Go to bed!";        // After 10pm


</script>

3 个答案:

答案 0 :(得分:1)

试试这个 -

html模板:

<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>

在您的组件中 -

export class SomeComponent implements OnInit {

    disabledstatus = false;

    constructor( ) { }

    ngOnInit() { }

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

}

看看这是否有帮助。

答案 1 :(得分:1)

最好的方法是使用[(ngModel)]

但是它不会生成你描述的那个对象,但是看到了行动: https://plnkr.co/edit/ojRw5lrXGONkKQ7yroKW?p=preview

你可以像这样简单地形成你的对象:

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 {}

答案 2 :(得分:0)

 <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>