Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
¿Cómo accedo a la propiedad "marcada" de un elemento de casilla de verificación HTML usando TypeScript?

Tengo el siguiente código HTML:

 <input type="checkbox" id="check-one">

El siguiente código CSS:

 .check-one { accent-color: #9d3039; }

Y el siguiente código 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);

Cada vez que veo la consola, todo lo que aparece es un error que dice: TypeError no capturado: checkInput is null

Me pregunto por qué sucede esto. ¿Por qué no devuelve True o False ya que checkInput.checked es un valor booleano? Además, ¿cómo manipulo esta propiedad para que la casilla se pueda marcar y desmarcar usando una línea de código en Typescript?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El elemento no existe cuando realiza su consulta porque su código se ejecuta al importar ese archivo TS. La plantilla para este componente aún no se ha inyectado en el DOM.

Debe esperar hasta que se inicialice la vista antes de consultar el DOM. Puede usar el gancho ngAfterViewInit para esto:

 export class AppComponent implements AfterViewInit { ngAfterViewInit() { const checkInput = document.getElementById('check-one') as HTMLInputElement; console.log(checkInput.checked); } }

Documentos para enlaces de ciclo de vida: https://angular.io/guide/lifecycle-hooks


En un proyecto angular, puede usar una referencia de plantilla y el decorador ViewChild para seleccionar un elemento 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); } }

Esto es más seguro ya que sabe exactamente qué elemento se está seleccionando y es más fácil hacer llamadas repetitivas.


En cuanto a establecer el valor de checked , es bastante simple a partir de ahí:

 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); } } }
about 4 years ago · Juan Pablo Isaza Report

0

puede usar el atributo onChange para activar una acción cuando está marcado

 <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form.submit()">

y luego puede usar el atributo de nombre para apuntar al atributo de valor

about 4 years ago · Juan Pablo Isaza Report

0

Realmente sugiero usar:

 <input type="checkbox" [(ngModel)]="check_box_value" />

para vincular la propiedad check_box_value para manipular el estado en dom.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!