Jam*_*mes 10 typescript angular-components angular angular-forms angular6
I'm working in forms and I have two components: my child component contains this formGroup Object :
employeeForm : FormGroup;
this.employeeForm = new FormGroup({
firstName:new FormControl(),
lastNAme:new FormControl(),
email:new FormControl()
});
Run Code Online (Sandbox Code Playgroud)
the child Component conatins just a small part of the form and the parent componant, contains the global form with submit button..
my issue is: I want in the Parent Component when I click on submit button I get the form group from my child component and push it to my global form in my parent component.
I add output in my child component :
@Output() onFormGroupChange: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();
Run Code Online (Sandbox Code Playgroud)
but I don't know how to let the submit button in parent Comp take the FormGroup object from my child component and proceed to push data...
do you have any idea on how to achieve this?
Thanks in advance.
Best Regards.
您可以将父表单传递给子组件:
<form [formGroup]="parentForm">
<child-form [form]="parentForm"></child-form>
<button (click)="submit()">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
在 child-form.component.ts 中,可以使用 addControl:
@Input() form; // this is parentForm
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form.addControl('firstName', new FormControl('', Validators.required));
}
Run Code Online (Sandbox Code Playgroud)
单击提交时,您也可以从子组件获取表单数据:
this.parentForm.value
Run Code Online (Sandbox Code Playgroud)
在子组件中做这样的事情:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit{
@Output() private onFormGroupChange = new EventEmitter<any>();
employeeForm = new FormGroup({
firstName:new FormControl(),
lastNAme:new FormControl(),
email:new FormControl()
});
public ngOnInit() {
this.onFormGroupChange.emit(this.employeeForm);
}
}
Run Code Online (Sandbox Code Playgroud)
和父组件: this.formCheck是我们可以在 html 中使用的实际 formGroup。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
formCheck :any = ''
public onFormGroupChangeEvent(_event) {
this.formCheck = _event;
console.error(_event, this.formCheck['controls'])
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7530 次 |
| 最近记录: |