奇怪的行为动态渲染输入类型复选框的类型 Angular 2+

2023-12-22

Need:

  • 创建类型属性为dynamic的输入。像这样的东西:<input id="{{ field.id }}" formControlName="{{ field.code }}" type="{{ field.type }}" />
  • 将上述输入与 FormGroup(反应式表单)内的“复选框”动态值一起使用。

Problem:

当我设置时出现问题type动态属性及其导致的原因是当我使用以下命令初始化 FormControl 时,在 DOM 中创建属性值为“false”的复选框false。因此 FormGroup 永远不会更新。

Notes:

  • 直接设置就不会出现这个问题类型=“复选框”因为它不生成 value 属性。
  • 该行为出现在最新版本的 Chrome 和 Firefox 中。
  • 该行为呈现在[电子邮件受保护] /cdn-cgi/l/email-protection and [电子邮件受保护] /cdn-cgi/l/email-protection(我没有在其他版本的 Angular 中测试过)

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

我真的很想了解这种行为是否正常以及原因。 谢谢!


目前有一个开放的票证,Igor Minar 和 Angular 团队正在研究它:

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

与此同时,您可以执行此解决方法:

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

在你的 html 中添加以下内容:

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

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

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 https://stackblitz.com/edit/angular-gitter-kzunhk?file=app/app.component.ts

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

奇怪的行为动态渲染输入类型复选框的类型 Angular 2+ 的相关文章

随机推荐