2017-12-06 12 views
2

아래의 SO 질문은 formbuilder 배열에서 formbuilder, 적절한 유효성 검사 및 동적 입력 필드 세트를 설정하는 데 도움이되었습니다.데이터 배열을 Angular2로 채우는 방법은 무엇입니까?

How to assign and validate arrays to forms in Angular2

http://plnkr.co/edit/YoqdBEo0MihaxdhHH1FV?p=preview

모든 것이 새로운 형태에 좋은 작품이 솔루션 코드 만 채울려고하는데 문제가 발생할 데이터베이스에서 양식을 밝혔다.

다음 코드를 사용하고 있습니다. initialValue에 이전 트랜잭션의이 양식에서 저장 한 이메일이 여러 개 있습니다. 다른 모든 양식 필드는 완벽하게 작동합니다. 배열을 조작하는 방법을 모르겠습니다.

ngOnChanges(changes: SimpleChanges): void { 
    if(this.form && changes['initialValue']){ 
    this.emails = changes['initialValue'].currentValue.emails; 
    this.form.patchValue(changes['initialValue'].currentValue); 
    //console.log('emails are now', this.emails); 
    //this.emailCtrl = this.fb.array([], Validators.minLength(1)); 
    //this.emails.forEach((email: any) => this.addEmail(email)); 
    } 
} 

줄을 주석으로 유지하면 배열의 첫 번째 전자 메일 만 양식에 올바르게 표시됩니다.

내가 줄의 주석을 제거하고 전자 메일의 새 목록으로 전자 메일 새로 고침을 시도하십시오. 다음과 같은 오류가 발생합니다.

ERROR Error: Cannot find control with path: 'emails -> 1 -> email' 
at _throwError (forms.js:2385) 
at setUpControl (forms.js:2255) 
at FormGroupDirective.addControl (forms.js:6606) 
at FormControlName._setUpControl (forms.js:7256) 
at FormControlName.ngOnChanges (forms.js:7169) 
at checkAndUpdateDirectiveInline (core.js:12092) 
at checkAndUpdateNodeInline (core.js:13598) 
at checkAndUpdateNode (core.js:13541) 
at debugCheckAndUpdateNode (core.js:14413) 
at debugCheckDirectivesFn (core.js:14354) 

답변

1
this.emailCtrl = this.fb.array([], Validators.minLength(1)); 
this.emails.forEach((email: any) => this.addEmail(email)); 

FormArray이 this.emailCtrl formArrayName 이외의 this.emailsCtrl해야 이메일하고 formControlName는 이메일

당신은 이름을 기반으로 액세스 할 수 있습니다 :

this.emailsCtrl = this.form.get('emails') as FormArray; 
    this.emails.forEach(email => this.addEmail(email)); 
+0

ooooh love 프로그래밍 :-p. 그럼 내가 먼저 비우기 전에 어떻게해야합니까? 현재 첫 번째 이메일을 반복하고 있습니다. – Kirby

+1

'removeAt (index)'를 사용하여 FormArray에서 항목을 제거 할 수 있습니다. – haifzhan

+0

감사합니다. 도움에 감사드립니다. :) – Kirby