Search code examples
angularangular-reactive-formsangular-forms

Separate Forms into Components in Angular


I have successfully built a page where it has two forms. I'm having difficulty on how to separate the two forms into separate components. I already added components for each forms. How would I do it the recommend and correct way?

Pls check my stackblitz here CLICK HERE

this.personalDetails = this.formBuilder.group({
  name: ["", Validators.required],
  email: ["", Validators.required],
  phone: ["", Validators.required],
});
this.addressDetails = this.formBuilder.group({
  city: ["", Validators.required],
  address: ["", Validators.required],
  pincode: ["", Validators.required],
});

Solution

  • To divide a large .html in two components you can make in three steps

    1. Use the same .html that the main.
    2. The necesaries variables you use @Input, so. e.g. for "personal-info" you need
          @Input() personalDetails:FormGroup
          @Input() personal_step = false;
    
    1. The functions are eventEmitters, so for personal-info you need
        @Output() next:EventEmitter<any>=new EventEmitter<any>()
    
    1. Change a bit the .html -really get out the "*ngIf="step==1" and change the (click)="next()" to use the Output
        <input (click)="next.emit(null)" .../>
    
    1. Some functions are necesary translate to the component
    2. You need copy also the .css. I choose put the .css in the styles.css (it's common to all the application

    I forked your stackblitz here