ngControl with ngFor in Angular2

前端 未结 1 1608
深忆病人
深忆病人 2020-12-11 06:53

Q1. Is it possible to have one Control ie:

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

to

相关标签:
1条回答
  • 2020-12-11 07:22

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

    (code not tested)

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

    0 讨论(0)
提交回复
热议问题