2017-03-21 6 views
0

개체 배열 데이터를 입력 컨트롤에 동적으로 할당하고 업데이트를 기반으로 논리를 구현하려는 요구 사항이 있습니다. 내 배열을 업데이트 할뿐만 아니라 중복 된 항목이있는 컨트롤에 입력 된 이름/데이터가 있는지 확인하기 위해 유효성 검사를 실행하고 싶습니다. . 유효성 검사를 위해 ReactiveForm 모듈을 사용했습니다. 그 성공 검증에 내가 직접 API에 대한 업데이트 된 구조를 통과 할 수 있도록 내가 같은 배열 구조를 만드는 방법angular2 (ReactiveForms)에서 동적 사용자 정의 유효성 검사를 추가하는 방법은 무엇입니까?

  1. - 그러나 나는이 문제 아래에 직면하고있다?
  2. 배열 객체의 id를 formControlName에 할당하는 방법은 현재 루프 인덱스를 할당하고 있습니다. 여기
    plunkar 참조 - https://plnkr.co/edit/RSBpT0sFSI1GDCp6K7VR?p=preview

구성 요소 : (추상)

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h3> Custom Group Validation</h3> 
     <form [formGroup]="myForm"> 
      <div class="left"> 
       names: <br> 
       <div formArrayName="names"> 
        <div *ngFor="let item of namesArray.controls; let i = index"> 
         <input type="text" [formControlName]="i"> 
         <button (click)="removeAt(i)">X</button><br> 
        </div> 
       </div> 

       <div *ngIf="namesArray.hasError('duplicate')"> 
        duplicate entries 
       </div> 
       <pre>Array value: <br>{{namesArray.value | json}}</pre> 
      </div> 
     </form> 
</div> 
    ` 
}) 

클래스 :

namesArray:FormArray = new FormArray([], this.customGroupValidation ); 
    dataArray: { custId: number, customerName: string }[] = [ 
{ custId: 101, customerName: 'John' }, 
{ custId: 102, customerName: 'Mike' }, 
{ custId: 103, customerName: 'Julia' }]; 

    ngOnInit():void{ 
     for(let ele of this.dataArray){ 
      this.namesArray.push(
      new FormControl(ele.customerName) 
     ); 
     } 
    } 

는 어떤 도움을 높이 평가!

답변

1

이 두 가지 문제를 처리하는 한 가지 방법은 FormGroup의 .valueChanges 이벤트를 구독하고 중복 조건에 대한 FormControl 값의 유효성을 검사하는 방법을 넣는 것입니다.

import { Component, NgModule, OnInit } from '@angular/core' 
import { BrowserModule } from '@angular/platform-browser' 
import { FormBuilder, FormGroup, FormArray, AbstractControl, Validators, FormControl, ReactiveFormsModule } from '@angular/forms' 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h3> Custom Group Validation</h3> 
     <form [formGroup]="customerFormGroup"> 
      <div class="left"> 
       names: <br> 
       <div> 
        <div *ngFor="let item of dataArray"> 
         <input type="text" [formControlName]="item.custId" [(ngModel)]="item.customerName"> 
         <div *ngIf="customerFormGroup.controls[item.custId] && customerFormGroup.controls[item.custId].errors"> 
         duplicate      
         </div> 
        </div> 
       </div> 
       <pre>Array value: <br>{{dataArray | json}}</pre> 
      </div> 
     </form> 
</div> 
    ` 
}) 
export class App implements OnInit { 
    customerFormGroup: FormGroup = new FormGroup({}); 
    dataArray: { custId: number, customerName: string }[] = [ 
    { custId: 101, customerName: 'John' }, 
    { custId: 102, customerName: 'Mike' }, 
    { custId: 103, customerName: 'Julia' }]; 

    ngOnInit(): void { 

    for (let ele of this.dataArray) { 
     let control: FromControl = new FormControl(ele.customerName); 
     this.customerFormGroup.addControl(ele.custId, control); 
    } 

    this.customerFormGroup.valueChanges.subscribe(
     data => this.onValueChanged(data) 
    ); 
    } 

    onValueChanged(data?: any) { 
    if (!this.customerFormGroup) return; 
    let formGroup = this.customerFormGroup; 
    var result = _.groupBy(formGroup.controls, c => { 
     if (c.value) return c.value.toLowerCase(); 
     else c.value; 
    }); 
    for (let prop in result) { 
     if (result[prop].length > 1) { 
     _.forEach(result[prop], function (item: any) { 
      if (item.dirty && item.value) { 
      item.setErrors({ 
       'duplicate': true 
      }); 
      } 
     }) 
     } 
    } 
    } 
} 

@NgModule({ 
    imports: [BrowserModule, ReactiveFormsModule], 
    declarations: [App], 
    bootstrap: [App] 
}) 
export class AppModule { } 
- 생성 및 ngOnInit()

코드 조각에 FormGroup하는 FormControl을 추가하는 동안

또한 custId 속성을 할당