2016-09-19 44 views
4

我想读的单选按钮值 - 在角2,阅读单选按钮值 - 角2

的index.html

<input type="radio" id="options1" name="function" value="create"> 
<input type="radio" id="options2" name="function" value="continue"> 

index.ts

@Component({ 
    selector: 'function', 
    templateUrl: './client/components/function/index.html', 
    styleUrls: ['./client/components/function/index.css'], 
    providers: [], 
    directives: [ROUTER_DIRECTIVES] 
}) 

我需要根据单选按钮值是否创建或继续在html中显示div。

我已经试过什么:

  1. 抓取的单选按钮的值在使用document.getElementById将输出文件 - 没有得到检测的性质checked
  2. 通过在打字稿中定义model,使用model.function读取该值。无法访问model变量,显然!
  3. 尝试使用[(ngModel)] - 也没有工作。

请为此建议一个周转。

回答

4

模板:

<input type="radio" id="options1" [(ngModel)]="myRadio" value="create"> 
<input type="radio" id="options2" [(ngModel)]="myRadio" value="continue"> 

然后在你的组件定义一个变量myRadio和初始化它是这样的: myRadio: string = ''

这个变量将获得选择的值。

,并使用JavaScript来控制Angular2 DOM元素,这是对angular2理念

+0

我试过的建议,但我发现了,说'不能读取属性“值”一个HTML错误未定义的。另外,如果我不应该使用Javascript修改DOM元素,建议我如何使用Angular 2来做到这一点。 –

+0

你需要在你的组件的构造函数中初始化变量: 'myRadio:string =''' –

+0

(或者把默认值例如'myRadio:string ='create'') –