Angular2中带有ngFor的ngControl [英] ngControl with ngFor in Angular2

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

问题描述

第一季度. 即:

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

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

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

第二季度.这些字段可以由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"/>

失败的方法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天全站免登陆