我有以下HTML代码:
<input type="checkbox" id="check-one">
以下CSS代码:
.check-one {
accent-color: #9d3039; }
以及以下TypeScript代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
arrayName = new Array(10000);
}
const checkInput = document.getElementById('check-one') as HTMLInputElement;
console.log(checkInput.checked);
每当我查看控制台时,我只得到一个错误:Uncaught : checkInput是空
我在想为什么会发生这种事?为什么它不返回真或假,因为checkInput.checked是一个布尔值?此外,如何操作此属性,以便可以使用类型记录中的一行代码检查和取消复选框?
发布于 2022-05-03 18:37:37
元素在您进行查询时不存在,因为您的代码在导入该TS文件时被执行。该组件的模板尚未注入到DOM中。
您需要等到视图初始化之后才能查询DOM。您可以为此使用ngAfterViewInit
钩子:
export class AppComponent implements AfterViewInit {
ngAfterViewInit() {
const checkInput = document.getElementById('check-one') as HTMLInputElement;
console.log(checkInput.checked);
}
}
生命周期挂钩的文档:https://angular.io/guide/lifecycle-hooks
在一个角度项目中,可以使用模板引用和ViewChild
装饰器来选择一个HTML:
<input type="checkbox" #checkOne />
export class AppComponent implements AfterViewInit {
@ViewChild('checkOne') _checkOne?: ElementRef;
get checkOne(): HTMLInputElement | undefined {
return this._checkOne?.nativeElement;
}
ngAfterViewInit() {
console.log(this.checkOne?.checked);
}
}
这是比较安全的,因为您知道确切地选择了哪个元素,并且更容易重复调用。
至于设置checked
的值,这里非常简单:
export class AppComponent implements AfterViewInit {
@ViewChild('checkOne') _checkOne?: ElementRef;
get checkOne(): HTMLInputElement | undefined {
return this._checkOne?.nativeElement;
}
ngAfterViewInit() {
if (this.checkOne) {
console.log(this.checkOne.checked);
this.checkOne.checked = true;
console.log(this.checkOne.checked);
}
}
}
发布于 2022-05-03 17:58:34
当选中时,可以使用onChange属性触发操作。
<input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form.submit()">
稍后,您可以使用name属性来针对value属性。
发布于 2022-05-03 19:49:37
我真的建议使用:
<input type="checkbox" [(ngModel)]="check_box_value" />
若要绑定属性check_box_value以操作dom上的状态,请执行以下操作。
https://stackoverflow.com/questions/72107177
复制相似问题