Reputation: 16022
Given a form declaration that looks like this:
this.form = this.fb.group({
party: this.fb.group({
name: [null, Validators.required],
givenName: [null, Validators.required],
surname: [null, Validators.required],
address: [""],
}),
role: this.fb.group({
mobile: [""],
landline: [""],
email: [null, (c: AbstractControl) => {
if (!c.value)
return null;
return Validators.email(c);
}],
})
});
I would like to move the party
form group to a new component, along with the validation / html etc.
What is the correct way to initialise this.form.party
, but pass it into a child component that will create the field and validators.
export class PartyDetailsComponent implements OnInit {
@Input group: FormGroup; // somehow created in the parent control?
constructor(
private readonly fb: FormBuilder,
private readonly logger: NGXLogger) {
}
ngOnInit() {
// how would I assign this correctly to the parent `party`
this.fb.group({
name: [null, Validators.required],
givenName: [null, Validators.required],
surname: [null, Validators.required],
address: [""],
});
};
}
Upvotes: 0
Views: 29
Reputation: 9873
One way I do this is by using @Output
in the child form component and emit the form on change.
With this approach, your party form can be used in isolation or it can be used in conjunction with any other form. It gives a nice re-use ability to the forms. You can throw them in a modal, use on a page, etc.
Template:
<party-form [data]="someInitialValue" (onChange)="form.get('party').patchValue($event)"></party-form>
Component:
export class PartyFormComponent implements OnInit {
@Output() onChange: EventEmitter<FormGroup> = new EventEmitter();
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = fb.group({});
// On change of form values, emit the onChange event again.
this.form.valueChanges.subscribe(() => this.onChange.emit(this.form));
}
@Input()
set data(data: Party) {
if (data) {
this.form.patchValue(data);
}
}
ngOnInit() {
// Emit onChange for the first time.
this.onChange.emit(this.form);
}
}
Upvotes: 1