用于从所选单选按钮中拉出ID和值的脚本不起作用

时间:2017-02-17 01:12:43

标签: angular typescript

我想从选定的单选按钮中同时提取idvalue。我在一些帖子和博客中遇到了这种代码风格,我决定在Angular 2中试一试。

var radios = document.getElementsByName('genderS');

for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        // do whatever you want with the checked radio
        alert(radios[i].value);

        // only one radio can be logically checked, don't check the rest
        break;
    }
 }

这是摘自Get Radio Button Value with Javascript

的摘录

我试图在我的Angular类中实现它的方式就像这样

selected = {value1: '', value2: ''}; //where I want the results to be stored.

//custom function with the snippet implemented
getSelected() {
    const radios = document.getElementsByName(this.quesForm.value.name);

    for (var i = 0, length = radios.length; i < length; i++) {
        if (radios[i].click){
            this.selected.value1 = radios[i].getAttribute("id");
            this.selected.value2 = radios[i].getAttribute("value");
            break;
        }
    }
}

//calling it here in an attempt to make sure it detects when the selection changes.
ngOnChanges() {
    this.getSelected();
    console.log(this.selected);
}

我的模板设置如下

<div *ngFor="let ans of quesForm.value.answers">
    <input type="radio" 
        [attr.name]  = "quesForm.value.name" 
        [attr.id]    = "ans.id"
        [attr.value] = "ans.answer"
    />
    <label>{{ans.answer}}</label>
</div>

我没有收到任何错误,但我也没有看到任何结果日志,我也在form标记之外显示结果以及保持空白。

<p>{{selected | json}}</p>

为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

使用数据绑定和DOM事件,如:

模板:

<div *ngFor="let ans of quesForm.value.answers">
    <input type="radio" 
        [attr.name]  = "quesForm.value.name" 
        [attr.id]    = "ans.id"
        [attr.value] = "ans.answer"
        (click)="selectAnswer(ans)"
    />
    <label>{{ans.answer}}</label>
</div>

组件:

selectAnswer(ans) {
    this.selected = ans;
    console.log(this.selected);
}

在Angular 2中,直接访问DOM是generally bad practice,通常表示您的设计存在问题。