我有两个组件FormComponent
和Test1Component
。
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的插件,请打开控制台查看日志。
答案 0 :(得分:3)