在 Angular2 中使用 ngFor 进行 ngControl [英] ngControl with ngFor in Angular2

查看:26
本文介绍了在 Angular2 中使用 ngFor 进行 ngControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Q1. 是否可以有一个控件即:

Q1. Is it possible to have one Control ie:

ValidNumber = new Control('', CustomValidators.number({min:1, max:10}))

要验证模板中所有类似类型的 input 字段吗?

to validate all similar type of input fields in the template ?

Q2.这些字段可以由 ngFor 生成吗?

Q2. Can these fields be generated by ngFor ?

失败方法 1: 验证有效,但值是耦合的.

FailedMethod 1: Validation works but values are coupled.

<input [ngFormControl]="ValidNumber" name="num1" type="number"/>
<input [ngFormControl]="ValidNumber" name="num2" type="number"/>

FailedMethod 2: 使用 formBuilder 时与上面相同.

FailedMethod 2: With formBuilder it's same as above.

<form [ngFormModel]="formBuiltWithFormBuilder">
  <input ngControl="ValidNumber" name="num1" type="number"/>
  <input ngControl="ValidNumber" name="num2" type="number"/>
</from>

<小时>

客观澄清:

  • 我正在尝试验证可能使用 ngFor 生成的表单字段并需要类似的验证.

  • I'm trying to validate form fields that might be generated with ngFor and require similar validation.

无需在其他地方重复定义类似的控件.

Without defining similar Controls repeatedly elsewhere.

我可以使用任何其他方法(如 #form="ngForm"ngModel)提取的值,所有我想要的都是 ngControl是验证.

Values I can extract with any other method like #form="ngForm" or ngModel, all I want from ngControl is Validation.

推荐答案

你也可以生成控件就没有问题了.

You can also generate the controls then there is no problem.

@Component({
  ...
  template: `
...
<input *ngFor="let c in controls" [ngFormControl]="c" name="c.name" type="number"/>
...
`
})
class MyComponent {
  // initialization with `['a', 'b', 'c']` just for demo purposes
  // these values probably come from outside - hence @Input()
  @Input() controlNames:string[] = ['a', 'b', 'c']; 

  controls: Control[];

  ngOnInit() {
    this.controlNames.forEach(
        v => this.controls.push(
            new Control('', CustomValidators.number{min:1, max:10})
        )
    );
  }
}

(代码未测试)

controls 需要在 controlNames 更改时更新.ngOnInit() 只运行一次.

controls needs to be updated when controlNames changes. ngOnInit() runs only once.

这篇关于在 Angular2 中使用 ngFor 进行 ngControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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