为什么ContentChild未定义?

时间:2017-04-07 12:52:08

标签: angular

我有两个组件FormComponentTest1Component

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.contentChildForm记录为undefined

如何解决?

这是我制作的https://plnkr.co/edit/xbTgRuSd7nBIrOWsE1zO的插件,请打开控制台查看日志。

1 个答案:

答案 0 :(得分:3)

我会在您的案例中使用@ViewChild,因为我在FormComponent

中看不到任何类型为Test1Component的可投放节点

<强> Modified Plunker