Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behavior rendering dynamically type of input type checkbox Angular 2+

Need:

  • Create an input with the type attribute dynamic. Something like this: <input id="{{ field.id }}" formControlName="{{ field.code }}" type="{{ field.type }}" />
  • Use the above input with "checkbox" dynamic value inside a FormGroup (reactive forms).

Problem:

The problem comes when i set the type attribute dynamically and what it causes is creating the checkbox in the DOM with an attribute value="false" when i initialize the FormControl with false. Therefore the FormGroup never gets updated.

Notes:

  • The problem does not happens when i set directly type="checkbox" because it does not generate the value attribute.
  • The behavior is presented in latests versions of Chrome and Firefox.
  • The behavior is presented in [email protected] and [email protected] (i haven't tested in other versions of Angular)

Behavior simulation: You can check the behavior by yourself on this link: https://stackblitz.com/edit/angular-gitter-ke3jjn

I really would like to understand if this behavior is normal and why. Thanks!

like image 739
Iván Portilla Avatar asked Sep 17 '25 16:09

Iván Portilla


1 Answers

There is currently an open ticket for that and Igor Minar and Angular team are looking into it:

https://github.com/angular/angular/issues/7329

In the meantime you can do this workaround:

onChange(event) {   
    this.form.get(event.target.attributes.formcontrolname.value)
    .setValue(event.target.checked);
}  

And in your html you add this:

<input id="check" type="{{'checkbox'}}" formControlName="checkOdd (change)="onChange($event)"/>

You can also add conditions inside the onChange to check on the type of the input and do something different with it, something like:

onChange(event) {  
    if(event.target.type === 'checkbox') {
      console.log('Checkbox'); 
    }
    if(event.target.type === 'text') {
      console.log('text'); 
    }

    this.form.get(event.target.attributes.formcontrolname.value)
    .setValue(event.target.checked);
}  

https://stackblitz.com/edit/angular-gitter-kzunhk?file=app/app.component.ts

like image 84
Nadhir Falta Avatar answered Sep 20 '25 08:09

Nadhir Falta