Search code examples
javascriptangulartypescriptradio-buttonchecked

angular 4 simply set a radiobutton in javascript


This has to be simple, but I don't want to use jQuery.
I need to set a specific radio button control. I have its Id, so I tried:

let radiobutton = document.getElementById("Standard");
radiobutton.checked = true;

I found examples on the web just like the above, but Typescript/Javascript gives me the error message: "Property 'checked' does not exist on type 'HTMLElement'"

Any ideas?

Thanks for your help.


Solution

  • Instead of doing document.getElementById, use @ViewChild and template variables. Here is an example:

    HTML:

    <input #checkbox1 type="checkbox" [checked]="true" (change)="onChange(1, checkbox1)"/>{{name1}}
    <br>
    <input #checkbox2 type="checkbox" (change)="onChange(2, checkbox2)"/>{{name2}}
    

    Typescript:

      name1 = 'Angular 2';
      name2 = 'Angular 4';
    
      @ViewChild("input1") input1;
      @ViewChild("input2") input2;
    
      ngOnInit(){
        this.input1.checked = true;
        console.log("Checkbox1 is checked -  ", this.input1.checked);
        console.log("Checkbox2 is checked -  ", this.input2.checked);
    
      }
    
      onChange(checkbox, item){
        console.log("Checkbox%d was checked", checkbox);
        console.log("Checkbox%d is checked -  ",checkbox, item.checked);
    
      }
    

    Stackblitz example