3

I am using Angular and TypeScript, and trying to enable/disable a textbox using a checkbox.

app.component.html

<input type="checkbox" value="true" (click)="check_en(value)">
<input type="text" id="text1" disabled>

app.component.ts

check_en(v1: any){
  if(v1 == true){
    document.getElementById('text1').setAttribute("disabled", "false");                  
  } else {
    document.getElementById('text1').removeAttribute("disabled")    
  }    
}
2
  • 1
    I'd strongly advise against manipulationg elements direclty. The whole point of Angular is (more or less) to do that for you ;) Commented Jun 9, 2020 at 7:45
  • Yes, as jBuchholz says, you have to go through the angular variables. Otherwise, you lose the benefits of the angular. Another thing, you should rather use 'if (v1)' or 'if (v1 === true)'. The first is shorter and the second is stricter. Commented Jun 9, 2020 at 7:58

2 Answers 2

3

Try to avoid modifying DOM directly with document.getElementById in Angular. You could achieve the same effect with other options.

Option 1: Two-way binding to the ngModel directive

Controller

export class AppComponent  {
  checkboxStatus: any;
  ...
}

Template

<input type="checkbox" [(ngModel)]="checkboxStatus" (click)="check_en(value)">
<input type="text" id="text1" [disabled]="!checkboxStatus">

Here we are two-way binding the value of the checkbox to the variable checkboxStatus using the ngModel directive.


Option 2: Template reference variable

Template

<input #inputCheck type="checkbox" (click)="check_en(value)">
<input type="text" id="text1" [disabled]="!inputCheck.checked">

Here a template reference variable inputCheck is used to refer to the checkbox within the DOM. Later it's property checked is bound to the text input property disabled to dynamically set it's value.

Sign up to request clarification or add additional context in comments.

4 Comments

thank for guide me. I am not good with angular. Now I tyr to learn it.
You could go through the Angular Tutorial here: angular.io/tutorial. It introduces some of the basics.
What does (click)="check_en(value)" do?
@xr280xr: It is the Angular equivalent of JS onclick attribute. It registers the event handler check_en(value) to be triggered when the click event is emitted. More info on Angular binding syntax here. Also sidenote: it's irrelevant to the solution. It's a carry over from OP's question.
0

to set checkbox checked, you have to checked=true and not by value.

For Example:

<input type="checkbox" checked=true (click)="check_en(value)">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.