而不是做document.getElementById,使用@ViewChild和模板变量。 下面是一个例子:
HTML:
<input #checkbox1 type="checkbox" [checked]="true" (change)="onChange(1, checkbox1)"/>{{name1}}
<br>
<input #checkbox2 type="checkbox" (change)="onChange(2, checkbox2)"/>{{name2}}
打字稿:
name1 = 'Angular 2';
name2 = 'Angular 4';
@ViewChild("input1") input1;
@ViewChild("input2") input2;
ngOnInit(){
this.input1.checked = true;
console.log("Checkbox1 is checked - ", this.input1.checked);
console.log("Checkbox2 is checked - ", this.input2.checked);
}
onChange(checkbox, item){
console.log("Checkbox%d was checked", checkbox);
console.log("Checkbox%d is checked - ",checkbox, item.checked);
}
Stackblitz example
为什么不使用角度结合? –
这不是在Angular2中做事的正确方法。但寻找https://www.w3schools.com/jsref/met_element_setattribute.asp –
我可以使用一些帮助,如何在Angular中“做对”。虽然我一直在阅读有关它,但我并不了解它的含义,它并没有沉入其中。你能说更多吗? –