Need:
<input id="{{ field.id }}" formControlName="{{ field.code }}" type="{{
field.type }}" />
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With