Asma Rahim Ali Jafri
Asma Rahim Ali Jafri

Reputation: 1373

Angular 8: Using a single form with multiple sibling components

Is there a way where I can use one single form using reactive forms and make it for use in all my other components?

I am making a basic CRUD app and it works fine. The problem is that each component has it's own template but I want to use the same form to create customer info, update the customer info using the same form that shows in the bootstrap modal.

I'm new and I can't wrap around the problem.

I have created a reactive-forms-component component that has the html for the reactive forms. But I don't know how to reuse them in each component.

Upvotes: 1

Views: 3320

Answers (2)

RandomCode
RandomCode

Reputation: 423

Yes, you can add to [formGroup]="form" any element and it will be a part of that form. It works for subgroups too. You should input @Input() form: FormGroup.

Any parent HTML element in the same component as your input field can have formGroup inputted.

Upvotes: 2

Mises
Mises

Reputation: 4603

Example CRUD with sorting list: https://sorting-list-angular.web.app/library Git of whole application: https://bitbucket.org/mises543/sorting-list/src/master/

It is simple application and NGXS in it is an overkill but im learning to. it's data state management. It's beter known as Redux.

You can study it.

template:

<div class="add-item-container">
  <mat-label>
    <h2>Add Media</h2>
  </mat-label>
  <section>
    <mat-form-field>
      <input matInput placeholder="Enter title:" type="text" [formControl]='title' required>
      <mat-error *ngIf="title.invalid && !''">{{getErrorTitle()}}</mat-error>
    </mat-form-field>
    <mat-form-field>
      <mat-select matInput placeholder="Category:" [formControl]="category" required>
        <ng-container *ngFor="let category of categories">
          <mat-option *ngIf="category != 'All'" [value]="category">{{category}}</mat-option>
        </ng-container>
      </mat-select>
      <mat-error *ngIf="category.invalid && !''">{{getErrorCategory()}}</mat-error>
    </mat-form-field>
    <mat-form-field>
      <input matInput [matDatepicker]="picker1" placeholder="Upload Date:" [formControl]="uploaded">
      <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
      <mat-datepicker #picker1></mat-datepicker>
    </mat-form-field>
    <div class="buttons">
      <ng-container *ngIf="data; then update; else add"></ng-container>
      <ng-template #add>
        <button mat-raised-button color="primary" (click)="onAdd()" [disabled]="title.invalid || category.invalid">Add
          item</button>
      </ng-template>
      <ng-template #update>
        <button mat-raised-button color="primary" (click)="onUpdate()"
          [disabled]="title.invalid || category.invalid">Update
          item</button>
      </ng-template>


      <button mat-raised-button color="primary" (click)="onCancel()">Cancel</button>
    </div>
  </section>
</div>

Most important in template are buttons so You display button Update when there is input data from parent component or add when there are no any data:

<ng-container *ngIf="data; then update; else add"></ng-container>
      <ng-template #add>
        <button mat-raised-button color="primary" (click)="onAdd()" [disabled]="title.invalid || category.invalid">Add
          item</button>
      </ng-template>
      <ng-template #update>
        <button mat-raised-button color="primary" (click)="onUpdate()"
          [disabled]="title.invalid || category.invalid">Update
          item</button>
      </ng-template>

form.component.ts im using @angular/material library just in case to pop a dialog:

categories = MediaOptions.CATEGORIES

  uploaded = new FormControl(new Date(), [Validators.required])
  title = new FormControl('', [Validators.minLength(5), Validators.required])
  category = new FormControl('', [Validators.required])

  constructor(private store: Store,
    private snackBar: SnackService,
    public dialogRef: MatDialogRef<AddItemComponent>,
    @Inject(MAT_DIALOG_DATA) public data?: any) {}

  ngOnInit(): void {
    if(this.data) {
      this.title.setValue(this.data.title)
      this.category.setValue(this.data.category)
      this.uploaded.setValue(this.data.uploaded)
    } else {
      this.uploaded.setValue(new Date())
    }
  }

Parent components with functions opening dialog:

constructor(private store: Store, private snackBar: SnackService, private dialog: MatDialog) { }

  async ngOnInit() {
    this.store.dispatch(new GetMedia())
  }

  editItem(payload: any) {
    this.dialog.open(AddItemComponent,
      { width: '500px', data: payload });
  }

  addItem() {
    this.dialog.open(AddItemComponent,
      { width: '500px' });
  }

Upvotes: 2

Related Questions