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

跟風遠走 提交于 2019-12-23 19:14:57

问题


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 angular@4.4.6 and angular@5.0.0 (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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/48652294/odd-behavior-rendering-dynamically-type-of-input-type-checkbox-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!