我有两个组件
1)FormComponent
有三个按钮Reset,Save and Add
2)Test1Component
有表单字段"名字"和"姓氏"
3)FormComponent
使用ng-content
加载Test1Component的内容
4)FormComponent
和Test1Component
都有saveForm()
方法
点击Save
按钮后,我尝试获取所有表单值,首先在Test1Component.saveForm()
处理它们,然后将处理后的表单值传递给FormComponent.saveForm()
现在写入的方式,首先执行FormComponent.saveForm()
会发出save
事件,触发Test1Component.saveForm()
现在,如何将处理后的数据从Test1Component.saveForm()
传回FormComponent.saveForm()
?
代码如下
form.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
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("Form save");
}
}
form.component.html
<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)="submitForm()"> {{saveBtnText}} </button>
<button class="btn btn-primary">{{addBtnText}}</button>
</div>
</div>
test1.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { FormComponent } from '../form/form.component';
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
styleUrls: ['./test1.component.css']
})
export class Test1Component{
complexForm : FormGroup;
constructor(private fb: FormBuilder){
this.complexForm = fb.group({
'firstName' : "",
'lastName': "",
'gender' : "Female",
'hiking' : false,
'running' : false,
'swimming' : false
});
}
saveForm(){
console.log("Child Form save");
}
}
test1.component.html
<app-form headerTitle="my header" (save)="saveForm($event)">
<div form-body>
<p>Fill this form</p>
<div class="jumbotron">
<form [formGroup]="complexForm">
<div class="form-group">
<label>First Name:</label>
<input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']">
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" type="text" placeholder="Doe" [formControl]="complexForm.controls['lastName']">
</div>
</form>
</div>
</div>
</app-form>
这就是它在UI中的外观
我也试过@Input,就像这样
@Input() formData; // In form.component.ts
并在test1.component.html
<app-form headerTitle="my header" [formData]="complexForm.value" (save)="saveForm($event)">
但在FormComponent.saveForm()
中,它提供了undefined
。