Question:
How to update properties value with event in template Angular?

Problem

(Working with Angular) Hello, I have a list of checkbox inputs like this:


<input (click)="onCheck(check1)" type="checkbox" />


The onCheck method is:


  onCheck(check:boolean){ check = !check } and a list of boolean properties like this:


public check1:boolean = false


When clicking in the checkbox input, the value of the property in the argument changes.


I tried:


  onCheck(check:any){

     check = !check


     this.check1 = check

  }


But I want the method to be dynamic for my checkbox list,


and in the template, I tried


<input (click)="onCheck(this.check1)" type="checkbox" />


With the same results. Can you tell me what I am doing wrong, why the value of the boolean property doesn't change?


Solution

  1. You can't change the check parameter in your onCheck function. The simplest way is to bind the check property to your check1 attribute.

  2. Also don't use click event as it doesn't provide the check value, use change instead:


Modify the template:



<input (change)="onCheck($event)" [checked]="check1" type="checkbox" />


Modify the callback:



onCheck(check:Event){

  const isChecked = (<HTMLInputElement>event.target).checked;

  this.check1 = isChecked;

}


Suggested blogs:

>What is the Idiomatic way to write a Typescript function with casting

>Why Redux-toolkit payload don't reconigze type in TypeScript?

>TypeScript: Define a type that refers type parameter from another line?

>Solve return type on TypeScript with boolean check doesn't seem to work

>How to fix TS2551: Property toSpliced does not exist on type Array

>Making an argument required if generic interface as no properties

>How to make argument required if generic interface as no properties?

>Cause a type error when a function returns any in TypeScript?

>Library isn’t work in Nestjs useGlobalFilters with library in TypeScript

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers