角度单选按钮:已选中 [英] Angular radio button :checked

查看:57
本文介绍了角度单选按钮:已选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通html和CSS中,我可以执行以下操作:

In ye ole plain html and css I can do the following:

input:checked+label {
  background-color: #f00;
}

<div class="col-xs-6">
  <input type="radio" id="template-1" name="template" value="template1" checked>
  <label for="template-1">Example 1</label>
</div>
<div class="col-xs-6">
  <input type="radio" id="template-2" name="template" value="template2">
  <label for="template-2">Example 2</label>
</div>

但是,当我尝试在ngModel的角形式内使用完全相同的代码段时,css最初不适用于负载.相反,您必须先单击其中一个按钮,然后才能应用它.

However, when I try to use the exact same snippet inside an angular form with ngModel, the css does not initially apply on load. Instead you have to click one of the buttons before it applies.

角形塞子

单选按钮似乎不符合checked属性?如何获取我的角度单选按钮以开始检查并应用CSS?

It appears that the radio button is not respecting the checked attribute? How can I get my angular radio button to begin checked and also apply the css?

推荐答案

请按以下说明更改组件

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

@Component({
  selector: 'my-app',
  template: `
  <h1>Hello {{name}}</h1>
        <div *ngFor="let example of examples" class="col-xs-6">
          <input type="radio" id="example.value" name="example" [(ngModel)]="template" [value]="example.value">
      <label for="example.value">{{example.display}}</label>
    </div>
  `,
  styles: [`input:checked + label{background-color: #f00;}`]
})
export class AppComponent implements OnInit{ 
  name = 'Angular';
  public examples = [
    { value: 1, display: 'Example 1' },
    { value: 2, display: 'Example 2' }
];
 template:string;


ngOnInit(){
   this.template = this.examples[0].value;
  }
}

还创建了一个plunkr

Also created one plunkr

plunkr

这篇关于角度单选按钮:已选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆