【问题标题】:Odd behavior rendering dynamically type of input type checkbox Angular 2+奇怪的行为动态呈现输入类型复选框Angular 2+
【发布时间】:2018-07-17 01:31:47
【问题描述】:

需要:

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

问题:

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

注意事项:

  • 直接设置type="checkbox"不会出现问题,因为它不会生成value属性。
  • 该行为出现在最新版本的 Chrome 和 Firefox 中。
  • 行为在 angular@4.4.6 和 angular@5.0.0 中呈现(我没有在其他版本的 Angular 中测试过)

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

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

【问题讨论】:

  • 我没有看到您的FormControl 在您的.ts 中定义。你看过动态表单文档吗? angular.io/guide/dynamic-form
  • 我正在使用 FormBuilder,它在内部创建所需的 FormControls。行为与手动 FormControl 相同。

标签: angular checkbox dynamic behavior


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这可能是同一问题的另一种形式。对于模型驱动的表单,如果您将输入类型动态设置为“电子邮件”,电子邮件验证将不起作用 - 不是浏览器或 Angular 验证。相反,它被验证为文本。 NgModel 和其他所有工作都可以。假设 field.type==='email':

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

    我几乎可以肯定我已经在一些早期的 4.x 中做到了这一点,并且它有效,但可能是记忆与老人玩的把戏。也许我使用 ngSwitch 或 ngIf 来交换整个输入,我想这也是目前唯一的解决方法。

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2010-10-05
      相关资源
      最近更新 更多