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

问题描述 投票:1回答:1

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获取这些项目?

angular2-forms angular-reactive-forms
1个回答
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 = '';
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.