2017-04-07 108 views
2

我有兩個組件FormComponentTest1Component爲什麼ContentChild未定義?

Test1Component使用ng-content顯示FormComponent

FormComponent.ts

import { Component, Input, Output, EventEmitter } from '@angular/core'; 

@Component({ 
    selector: 'app-form', 
    template:` 
     <div class="panel panel-default fcs-form"> 
     <div class="panel-header form-header"> 
       {{headerTitle}} 
     </div> 

     <div class="panel-body form-body"> 
      <ng-content select="[form-body]"></ng-content> 
     </div> 
     <div class="panel-footer text-center form-footer"> 
       <button class="btn btn-primary">{{resetBtnText}}</button> 
      <button class="btn btn-primary" (click)="saveForm()"> {{saveBtnText}} </button> 
      <button class="btn btn-primary">{{addBtnText}}</button> 
     </div> 
     </div> 
    ` 
}) 
export class FormComponent{ 
    @Input() headerTitle:string = "Header Title"; 
    @Input() saveBtnText:string = "Save"; 
    @Input() resetBtnText:string = "Reset"; 
    @Input() addBtnText:string = "Add"; 
    @Output() save:EventEmitter<any> = new EventEmitter(); 

    constructor(){} 

    saveForm(e: any){ 
    this.save.emit("save"); 
    console.log("FormComponent save"); 
    } 
} 

Test1Component.ts

import { Component, Inject, OnInit, ContentChild } from '@angular/core'; 
import { FormGroup, FormBuilder } from '@angular/forms'; 
import { FormComponent } from './form.component'; 

@Component({ 
    selector: 'app-test1', 
    template: ` 
    <app-form headerTitle="my header" (save)="saveForm(complexForm.value, $event)"> 
     <div form-body> 

      <div class="jumbotron"> 
       <form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)"> 

        <div class="form-group"> 
         <label>First Name:</label> 
         <input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']"> 
        </div> 

       </form> 
      </div> 

     </div> 
    </app-form> 
    ` 
}) 
export class Test1Component { 
    @ContentChild(FormComponent) contentChildForm: FormComponent; 

    complexForm : FormGroup; 

    constructor(private fb: FormBuilder){ 
    this.complexForm = fb.group({ 
     'firstName' : "", 
     'lastName': "", 
     'gender' : "Female", 
     'hiking' : false, 
     'running' : false, 
     'swimming' : false 
    }); 
    } 

    saveForm(){ 
    console.log(this.contentChildForm); 
    debugger; 
    console.log("Test1Component save"); 
    return true; 
    } 
} 

爲什麼Test1Component.saveForm()正在記錄this.contentChildFormundefined

如何解決?

這是我製作的https://plnkr.co/edit/xbTgRuSd7nBIrOWsE1zO,請打開控制檯查看日誌。

回答

3

我會用@ViewChild在你的情況,因爲我在你Test1Component

Modified Plunker

+1

事實上,我認爲是正確的答案沒有看到FormComponent類型的任何可投影的節點。這可能對知道何時使用'@ ViewChild'和'@ ContentChild'有用:http://stackoverflow.com/questions/34326745/whats-the-difference-between-viewchild-and-contentchild – SrAxi

+1

@SrAxi這使事情概念上清晰易懂 –

+0

@yurzui使用ViewChild引用將數據傳遞給孩子是否明智?或使用輸入裝飾器? –