奇数行为动态呈现输入类型复选框Angular 2+的类型 [英] Odd behavior rendering dynamically type of input type checkbox Angular 2+

查看:62
本文介绍了奇数行为动态呈现输入类型复选框Angular 2+的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要:

  • 创建一个具有动态type属性的输入.像这样:<input id="{{ field.id }}" formControlName="{{ field.code }}" type="{{ field.type }}" />
  • 将上面的输入与FormGroup(反应性表单)中的复选框"动态值一起使用.
  • 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).

问题:

当我动态设置 type 属性时会出现问题,当我使用 false .因此,FormGroup永远不会更新.

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.

注释:

  • 当我直接设置 type ="checkbox" 时,不会发生此问题,因为它不会生成value属性.
  • 该行为在最新版的Chrome和Firefox中得以体现.
  • 该行为在angular@4.4.6和angular@5.0.0中进行了介绍(我尚未在Angular的其他版本中进行测试)
  • 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)

行为模拟: 您可以通过以下链接自行检查行为: https://stackblitz.com/edit/angular -gitter-ke3jjn

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!

推荐答案

当前有一张公开票,Igor Minar和Angular团队正在调查中:

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);
}  

然后在您的html中添加以下内容:

And in your html you add this:

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

您还可以在onChange内添加条件以检查输入的类型并对其进行不同的操作,例如:

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

这篇关于奇数行为动态呈现输入类型复选框Angular 2+的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆