【问题标题】:How to Validate Angular 2 FormArray for length and Regex如何验证 Angular 2 FormArray 的长度和正则表达式
【发布时间】:2018-10-15 22:16:22
【问题描述】:

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 之类的响应式表单/模型驱动表单方法。 如何使用 ngModel 获取这些项目?

【问题讨论】:

    标签: angular2-forms angular-reactive-forms


    【解决方案1】:

    我希望这会有所帮助。

    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 = '';
      }
    }

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 2022-11-23
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      相关资源
      最近更新 更多