Iván Portilla
Iván Portilla

Reputation: 471

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

Need:

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:

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!

Upvotes: 3

Views: 561

Answers (2)

Nadhir Falta
Nadhir Falta

Reputation: 5257

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

Upvotes: 1

funkizer
funkizer

Reputation: 4897

This might be another flavor of the same issue. With a model driven form, if you set an input type dynamically to 'email', email validation won't work - not browser or Angular validation. Instead, it gets validated as text. NgModel and all else works though. Assume field.type==='email':

<input *ngFor="field in fields" [type]="field.type" [(ngModel)]="field.model" [required]="field.required"/>

I'm almost sure I've done this with some early 4.x and it worked, but can be memory playing tricks with old man. Maybe I used ngSwitch or ngIf to swap the whole inputs instead, which I guess is also the only work-around at the moment.

Upvotes: 1

Related Questions