2017-02-20 50 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)到您的窗體:

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

在你父母的HTML通過formGroup給你的孩子:

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

和子模板:

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

而且不要忘記用Input來標記從父母收到的表格組:

@Input() timeGroup: FormGroup; 

然後你就可以與訪問time值(在父):

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

還要注意,你不需要任何活動,如keyup,這些變化將沒有他們的父母被逮住。

Sample Plunker

+0

這個答案對您有幫助嗎? :) – Alex

+0

是的..它沒有..謝謝一噸:) – sam1990

+0

太棒了!然後請考慮接受答案,通過點擊這個答案的投票下的灰色滴答,所以問題被標記爲解決:)有一個偉大的一天,快樂的編碼:) – Alex

相關問題