这必须很简单,但我不想使用 jQuery。
我需要设置一个特定的单选按钮控件。我有它的 ID,所以我尝试了:
let radiobutton = document.getElementById("Standard");
radiobutton.checked = true;
我在网上找到了类似上面的例子, 但 Typescript/Javascript 给了我错误消息: ““HTMLElement”类型上不存在“checked”属性”
有什么想法吗?
感谢您的帮助。
最佳答案
不要使用 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}}
typescript :
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);
}
关于javascript - Angular 4只需在javascript中设置一个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46350620/