2017-02-20 1 views
2

폼 빌더를 통해 빌드 된 폼을 가진 컴포넌트가 있습니다. 이제 폼 컨트롤로 입력 상자가 하나만있는 컴포넌트를 포함해야합니다.FormControl Angular2로 컴포넌트 포함

add.ts

this.newForm = this.fb.group({ 
     name: ['', [Validators.required]], 
     surname:['', [Validators.required]], 
     time: '' 
    }); 

가 다른 구성 요소로 포함하는 "시간"있다.

add.html

<div class="form-group"> 
      <label class="col-md-3 control-label" for="name">{{'forms.newForm.label.configuration.name' | translate}}</label> 
      <div class="col-md-3"> 
       <input type="text" formControlName="name" placeholder="placeholder" 
        class="form-control input-md" type="text"> 
       <small *ngIf="!newForm.controls.name.valid && newForm.controls.name.dirty" class="text-danger"> 
       Name is required. 
       </small> 
      </div> 

      <label class="col-md-3 control-label" for="surname">{{'forms.newForm.label.configuration.name' | translate}}</label> 
      <div class="col-md-3"> 
       <input type="text" formControlName="surname" placeholder="placeholder" 
        class="form-control input-md" type="text"> 
       <small *ngIf="!newForm.controls.surname.valid && newForm.controls.name.dirty" class="text-danger"> 
       Surname is required. 
       </small> 
      </div> 
      </div> 

time.html

<div> 
    <div class="col-md-7"> 
    <input class="form-control input-md" type="text" (keydown)="eventHandler($event)" maxlength="11"> 
    <small *ngIf="!validTime" class="text-danger"> 
     Invalid time 
    </small> 
    </div> 
</div> 

제가 주요 형태의 구성 요소로서 "시간"폼 제어 방법을 포함 그래서 this.newForm 통해 값을 액세스 할 .controls [ '시간']. 값 ??

+0

이 부모와 자식입니까? – Alex

+0

@ AJT_82 예 .. 부모님과 자식입니다 – sam1990

답변

3

단일 Form Control은 하위 구성 요소로 별도로 전달할 수 없으므로 formGroup 내에 전달되어야합니다. 그래서 양식에 (여기 timeGroup 이름) 그룹을 추가 :

<time-comp [timeGroup]="newForm.controls.timeGroup"></time-comp> 

와 자식 템플릿 :

<div [formGroup]="timeGroup"> 
    <input formControlName="time"> 
</div> 

그리고

당신의 부모 HTML에서
this.newForm = this.fb.group({ 
     name: ['', [Validators.required]], 
     surname:['', [Validators.required]], 
     timeGroup: this.fb.group({ 
     time: '' 
     }) 
}); 

자녀에 formGroup 전달 부모에게서받은 양식 그룹을 Input으로 표시하는 것을 잊지 마십시오.

는 그런 다음에 (부모의)을 time 값에 액세스 할 수 있습니다

this.newForm.get('timeGroup').get('time').value; 

은 또한 당신이 변화가 그들없이 부모에 의해 사로 잡았되고, keyup 같은 이벤트를 필요로하지 않는 것을 알 수 있습니다.

Sample Plunker

+0

이 답변이 도움이 되었습니까? :) – Alex

+0

예 .. 그랬어. 고마워. :) – sam1990

+0

위대한! 그런 다음이 답변의 투표 아래에있는 회색 눈금을 클릭하여 답변을 수락하는 것을 고려하십시오. 그래서 질문은 해결됨으로 표시되어 있습니다 :) 멋진 하루 되세요. 행복하게 코딩하십시오 :) – Alex