动态复选框的Angular 4触发事件

时间:2018-04-26 10:45:37

标签: javascript angular for-loop

我创建了一个div元素和动态复选框以及更改功能。但是点击复选框后,该函数不会被调用

我的代码

@Component({
    selector: 'Dropdown',
    template: `<div class="select">
        <div class="selectBox" (change)="Checkboxes()">
          <select multiple>
            <option id='Option' (click)='Click()'>Select an option</option>
          </select>
        </div>
        <div id="checkboxesdiv">
      </div></div>`
})

ngOnInit 中,我已使用动态值声明了字符串,并将其分配给模板的innerHtml

    let option = "";
    for(let item of DBdata){
    option += "<label for='" + item.id+ "' title='" + item.des+ "'><input class='Optioninputclass' (change)='ChangeFn()' type='checkbox' id = '" + item.id+ "'/>" + item.des+ "</label>"
    }

    var select = document.getElementById("checkboxesdiv");
    select.innerHTML = this.optionValue;

单击复选框时未调用 ChangeFn 。我也尝试了(click)='ChangeFn()',但结果相同。提前谢谢。

1 个答案:

答案 0 :(得分:0)

在构建期间编译Angular模板。当您通过innerHTML动态设置内容时,您不能使用角度语法(或者您可以,但它只是被忽略)。您应该做的是使用* ngFor。

在模板中创建检查
@Component({
    selector: 'Dropdown',
    template: `<div class="select">
        <div class="selectBox" (change)="Checkboxes()">
        <select multiple>
            <option id='Option' (click)='Click()'>Select an option</option>
        </select>
        </div>
        <div id="checkboxesdiv">
            <label [for]="item.id" [title]="item.des" *ngFor="let item of DBdata">
                <input class="Optioninputclass" (change)="ChangeFn()" type="checkbox" [id]="item.id"/>{{ item.des }} 
            </label>
        </div>
    </div>`
})

只需确保DBdata是组件中的公共字段,因此模板可以访问它。