如何验证Angular 2 FormArray的长度和正则表达式

时间:2018-05-05 16:28:54

标签: angular2-forms angular-reactive-forms

app.component.ts

import { Component,OnInit } from '@angular/core';
import {FormControl,FormGroup,FormArray,FormBuilder} from '@angular/forms'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  form=new FormGroup({
    topics:new FormArray([])
  })

  addTopic(topic:HTMLInputElement){
    (this.form.get('topics') as FormArray).push(new FormControl(topic.value));
    topic.value='';
  }
}

app.component.html

<form>
<input type="text" class="form-control" (keyup.enter)="this.addTopic(topic)" #topic />
<ul class="list-group">
  <li class="list-group-item" *ngFor="let topic of form.get('topics').controls">
    {{topic.value}}
  </li> 
</ul>
</form>

我使用Angular FormArray创建了一个多输入控件,但是我如何才能为最少2个项目(长度= 2)验证相同,并且只接受整数值。 如何添加Validators.minlength,如Reactive Form / Model Driven Form Approach。 如何使用ngModel获取这些项目?

1 个答案:

答案 0 :(得分:0)

我希望这会有所帮助。

import {
  Component,
  OnInit
} from '@angular/core';
import {
  FormControl,
  FormGroup,
  FormArray,
  FormBuilder
} from '@angular/forms'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 6';
  form = new FormGroup({
    topics: new FormArray(this.formBuilder.control(''), [Validators.reqired, Valiadtors.minlength(2)], Validators.Paterrn("^[0-9]*$"))
  ])

  addTopic(topic: HTMLInputElement) {
    (this.form.get('topics') as FormArray).push(new FormControl(topic.value));
    topic.value = '';
  }
}