Should I use two components for edit and create form in angular?
you could create one common form component, that accept @Input is a FormGroup, then create Edit and Create form, setup form (edit form will have values), passing your form to common form component:
Common
@Component({
selector: 'tpc-cm-form',
template: `
<div [formGroup]="formGroup">
<input formControlName="example" type="text"> <br>
<textarea formControlName="sectionContent"></textarea>
</div>
`
})
export class CMForm {
@Input() formGroup: FormGroup;
}
Create
@Component({
selector: 'tpc-cr-form',
template: `
<form [formGroup]="form">
<tpc-cm-form [formGroup]="form"></tpc-cm-form>
</form>
`
})
export class CreateForm {
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
example: '',
sectionContent: ''
});
}
}
Edit
@Component({
selector: 'tpc-ed-form',
template: `
<form [formGroup]="form">
<tpc-cm-form [formGroup]="form"></tpc-cm-form>
</form>
`
})
export class EditForm {
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
example: '',
sectionContent: ''
});
// fetch data from API for example
this.form.patchValue({
example: 'Simple data',
sectionContent: 'Content textarea'
});
}
}
online demo: https://plnkr.co/edit/NWgzGdUc9cDkKujPgrl4?p=preview