0
votes

I have one component that is getting a collection of documents from firestore and displaying them in a table, and another component with a reactive form to add new entries to the table.

I'm working on allowing a user to click a button on the table that will then populate the reactive form component with the data from that row.

Here is my form in componentA:

  inventoryForm = new FormGroup({
    name: new FormControl('', Validators.required),
    date: new FormControl('', Validators.required),
    amount: new FormControl('', Validators.required),
    comment: new FormControl('', Validators.required),
    carried: new FormControl('', Validators.required),
  });

If I include a button in componentA.html that calls a function like this in componentA

  testPatch() {
    this.inventoryForm.patchValue({ name: 'Test123' });
     }

The form is updated as expected (name input is populated with Test123).

If however, I have a button in componentB.html, that calls a function in componentB that then calls a patchValue function in componentA, the patch doesn't work.

I'm importing componentA into componentB in order to call the function while passing through a document ID.

Is there something simple I'm missing, or a better way to try and do this?

Update: I'm running into an issue where the formgroup is returning null, I'm going to add some additional pieces of code.

I had to update the [providers] in app.module.ts to add FormGroupDirective, or I would get a stackinjector error trying to initialize FormGroupDirective in the constructor of my component.

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
import { InventoryService } from './inventory.service';
import { inventory_item } from './inventory_item';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {


  constructor(private inventoryService: InventoryService) {
  }

  inventoryForm = new FormGroup({
    name: new FormControl('', Validators.required),
    date: new FormControl('', Validators.required),
    amount: new FormControl('', Validators.required),
    comment: new FormControl('', Validators.required),
    carried: new FormControl('', Validators.required),
  });

  submitted = false;
  update = false;
  submittedItem: inventory_item = {
    name: '',
    date: '',
    amount: 0,
    comment: '',
    carried: '',
  }

  onSubmit() {
    this.submitted = true;
    const name = this.inventoryForm.get('name').value;
    const date = this.inventoryForm.get('date').value;
    const amount = this.inventoryForm.get('amount').value;
    const comment = this.inventoryForm.get('comment').value;
    const carried = this.inventoryForm.get('carried').value;
    this.inventoryService.addInventory({ name, date, amount, comment, carried })
    this.submittedItem = this.inventoryForm.value
  }
}

app.component.html

<app-inventory-list></app-inventory-list>
<div [hidden]="submitted">
  <form [formGroup]="inventoryForm" (ngSubmit)="onSubmit()">
    <label>
      Item Name:
      <input type="text" formControlName="name">
    </label>

    <label>
      Date Added:
      <input type="text" formControlName="date">
    </label>

    <label>
      Amount:
      <input type="number" formControlName="amount">
    </label>

    <label>
      Comment
      <input type="text" formControlName="comment">
    </label>

    <label>
      Carried by:
      <input type="text" formControlName="carried">
    </label>
    <br />
    <button type="submit" [disabled]="!inventoryForm.valid">Submit</button>
  </form>
</div>
<app-item-management></app-item-management>

<div [hidden]="!submitted">
  <h2>Item Added</h2>
  Name: {{submittedItem.name}}
  <br />
  Date: {{submittedItem.date}}
  <br />
  Amount: {{submittedItem.amount}}
  <br />
  Comment: {{submittedItem.comment}}
  <br />
  Carried by: {{submittedItem.carried}}
  <br />
  <button type="button"
          class="btn btn-default"
          (click)="inventoryForm.reset();
          submitted=false">
    New Loot!
  </button>
</div>

item-management.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { InventoryService } from '../inventory.service';
import { FormGroupDirective, FormGroup, ControlContainer, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-item-management',
  templateUrl: './item-management.component.html',
  styleUrls: ['./item-management.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ItemManagementComponent implements OnInit {


  constructor(private inventoryService: InventoryService, private parentForm: FormGroupDirective) {
  }

  editItem: any;

  ngOnInit() {
  }

  testPatch() {
    //this.parentForm.form.patchValue({ name: 'Test123' });
    console.log(this.parentForm.form)
  };

  updateInventory(updateId: string) {
  //this.parentForm.inventoryForm.patchValue({ name: 'Test123' });
    this.parentForm.form.patchValue({ name: 'Test123' });
    this.inventoryService.getUpdateInventoryItem(updateId)
      .then((doc) => {
        if (doc.exists) {
          console.log("Document data:", doc.data());
          this.editItem = doc.data();
          console.log("EditItem:", this.editItem)

        } else {
          console.log("No such document!");
        }
      }).catch(function (error) {
        console.log("Error getting document:", error);
      }); 
  };

}

item-management.component.html

<button type="button"
        class="btn btn-default"
        (click)="testPatch()">
  Patchtest
</button>

So when I click my 'patch test' button, the console prints 'null' for the returned object, or I get:

Cannot read property 'patchValue' of null
    at ItemManagementComponent.push..
1

1 Answers

3
votes

Better Approach is to Create Top level form then wrap your child component inside that component.

app.component.ts

<form [formGroup]="form">
    <input type="text" formControlName="name">
  <app-component-b></app-component-b>
</form>

Inside child component use Viewproviders to get parentform instance to patch the value using

componentb.component.ts

import { Component, OnInit } from '@angular/core';
import { ControlContainer, FormGroupDirective } from '@angular/forms';
@Component({
  selector: 'app-component-b',
  templateUrl: './component-b.component.html',
  styleUrls: ['./component-b.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ComponentBComponent implements OnInit {
  constructor(private parentForm: FormGroupDirective) { }
  ngOnInit() {
  }
  patchValue() {
    this.parentForm.form.patchValue({ name: 'fromChildComponentB' });
  }

}

Example: https://stackblitz.com/edit/angular-jteaiw