简体   繁体   English

替换 Angular 中的 document.getElementById('checkBox')

[英]Replacing document.getElementById('checkBox') in Angular

I am trying to replace the document.getElementById from:我正在尝试从以下位置替换document.getElementById

target = document.getElementById('checkBox') as HTMLInputElement;

I have tried:我努力了:

  1. adding #target in html在 html 中添加#target
  2. import ElementRef and ViewChild导入 ElementRef 和 ViewChild
  3. add @ViewChild('target') public target: ElementRef;添加 @ViewChild('target') 公共目标:ElementRef;
  4. this.target.nativeElement.checked = false; this.target.nativeElement.checked = false;

and this does not seem to be working.这似乎不起作用。

you don't have to use template reference (#target) or ViewChild to change the value of the checkbox input.您不必使用模板引用 (#target) 或 ViewChild 来更改复选框输入的值。

you have two options:你有两个选择:

1- Two-way Data Binding 1-双向数据绑定

create a property inside your component and bind it to the input(checkbox) using [(ngModel)]="property_name" now you can change the value of this property and the checkbox will be changed在您的组件中创建一个属性并使用[(ngModel)]="property_name"将其绑定到输入(复选框)现在您可以更改此属性的值并且复选框将被更改

2- Reactive form 2-反应形式

if you are using this input inside a reactive form, just add a FormControl to the FormGroup you are using and use this FormControl to change the value如果您在反应式表单中使用此输入,只需将 FormControl 添加到您正在使用的 FormGroup 并使用此 FormControl 更改值

this.form_group_name.get('form_control_name').setValue(true / false);

this.form_group_name.get('form_control_name').patchValue(true / false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular document.getElementById 不能动态使用插值 - Angular document.getElementById not working with interpolation dynamically angular4 / typescript中的document.getElementById替换? - document.getElementById replacement in angular4 / typescript? Angular 测试 - 如何在 angular 测试中模拟 document.getElementbyId? - Angular test - how to mock document.getElementbyId in angular test? Angular 12 对象在 document.getElementById(elementId) 中可能为“null” - Angular 12 Object is possibly 'null' in document.getElementById(elementId) document.getelementbyid 始终在 angular 13 中返回 null - document.getelementbyid always returns null in angular 13 带有 Nrwl/Nx 的 Angular SSR - 外部库调用 document.getElementById - Angular SSR with Nrwl/Nx - external library calls document.getElementById 无法使用 document.getelementById(id) 将焦点设置在 angular 编辑器上 - Unable to set focus on angular editor using document.getelementById(id) 打字稿中是否有“document.getElementById('first')”的替代方案? - Is there any alternative of `document.getElementById('first')` in typescript? 如何通过 document.getElementById inAngular 更改显示 - How to change display by document.getElementById inAngular 是否有 Angular 的做法: document.getElementById(id).style.display = "none"; - Is there an Angular way of doing: document.getElementById(id).style.display = "none";
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM