2017-05-29 135 views
0

在咋OLE普通的HTML和CSS我可以执行以下操作:角单选按钮:检查

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的最初不适用的负载。相反,您必须在适用之前单击其中一个按钮。

angular plunkr

看来,单选按钮不尊重checked属性?我如何让角度单选按钮开始检查并应用css?

回答

1

请改变你的组件,如下

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

plunkr

+0

谢谢 - 完美。 – Zze

+0

所以我只是有一个非常奇怪的bug'ngModel'不再改变。我通过使'id'和'for'属性绑定来解决这个问题。即'[for] =“example.value”' – Zze

-1

这个答案是AngularJS。 OP想要的答案对角...

随着角度也可以根据NG-模型

<input type="radio" ng-model="bool" ng-class="bool ? 'true' : 'false'">

该值增加一个类应该添加类“真”时$范围。布尔是真实的(或无线检查)

没有测试这一点,但它应该工作或以某种方式至少帮助。

+0

对不起,我正在寻找angular而不是angularJS。 – Zze

+1

哎呀,我的坏... –

0

更新Pluker

http://plnkr.co/edit/xCZKeAx8Q2e2Ge5istuE?open=app%2Fapp.component.ts&p=preview

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

这是不是与形式的正常工作。即使设置了初始值,它也不会反映在表单值中:http://plnkr.co/edit/cXfkRAsYNoWPWjNw5Zqp?open=app%2Fapp.component.ts&p=preview另外,它并不反映返回到'template1'的值无线电被点击... – Alex

+0

@ AJT_82烨我试图去弄清楚它没有反映在我们天玑有ngModel ATTR。我们需要绑定的检查ngModel,但它不是发生 –