ccocker
ccocker

Reputation: 1236

Angular 2 Ngrx Store: Updating Array

I currently have an angular2 CRM app based on ngrx/store architecture. I have the CRUD functions for updating, listing and adding customers working fine and all tied up to Firebase Database using ngrx/effects.

To keep the smart component in sync with the store i have the following code. Again all working fine, however i am unsure about how to update an array in the form - see code below: -

This is where i update the form with the data from the store

if (this.customer) {

          this.customerForm.get('name').setValue(this.customer.name);
          this.customerForm.get('overview').setValue(this.customer.overview);
          this.customerForm.get('imagePath').setValue(this.customer.imagePath);

          console.log("ngOnChanges", this.customer);

        }

I want to do a similar thing with address form but unsure how to do the above to populate the array object in the form. Any ideas / suggestions welcome

When i log the console below i actually have the address details just need to know how to get them into the form object.

Object
addresses: Array(2)
0:Object
1:Object
length:2
imagePath:"http://www.bytes.co.uk/application/themes/bytes/img/bytes-technology-group.svg"
name:"Bytes Technology Group Emirates LLC"
overview:"Kronos Re-Seller for the Middle East and GCC Countries and Egypt"
parentId:"-KcRRsAGRYASXNU3gO_F"

Full Customer Detail Smart Component

import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, OnChanges } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from "@angular/forms";

// Mojito Models
import { CustomerModel } from '../../models/customer-model';
import { AddressType } from '../../../shared/models/address.model';

@Component({
  selector: 'mj-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomerDetailComponent implements OnInit, OnChanges {

  @Input() customer: CustomerModel;
  @Output() updatedCustomer: EventEmitter<CustomerModel> = new EventEmitter<CustomerModel>();
  @Output() showView: EventEmitter<string> = new EventEmitter<string>();
  @Output() customerId: EventEmitter<string> = new EventEmitter<string>();

  customerForm: FormGroup;
  addressForm: FormGroup;

  addressTypes: AddressType[] = [
    { "id": 1, "name": "Work" },
    { "id": 2, "name": "Home" },
  ]

  private newAddressGroup() {
    return new FormGroup({
      type: new FormControl,
      street: new FormControl,
      city: new FormControl,
      country: new FormControl,
      postalCode: new FormControl
    })
  }

  get addresses() {
    return (this.addressForm.get('addressGroups') as FormArray).controls;
  }


  constructor(private fb: FormBuilder) {

    this.customerForm = this.fb.group({
      name: [null, Validators.required],
      overview: [null, Validators.required],
      imagePath: [null, Validators.required],
    });

    this.addressForm = this.fb.group({
      addressGroups: this.fb.array([])
    });
  }

  ngOnChanges() {

    if (this.customer) {

      this.customerForm.get('name').setValue(this.customer.name);
      this.customerForm.get('overview').setValue(this.customer.overview);
      this.customerForm.get('imagePath').setValue(this.customer.imagePath);

      console.log("ngOnChanges", this.customer);

    }

  }

  ngOnInit() {



  }

  onAddAddressGroup() {
    const fa = this.addressForm.controls["addressGroups"] as FormArray;

    fa.push(this.newAddressGroup());

  }

  onSaveAddress() {
    const addresses = this.addressForm.controls["addressGroups"].value;
    this.customer.addresses = addresses;
    this.onSaveCustomer();
  }

  onSaveCustomer() {

    this.customer = Object.assign(this.customer, this.customerForm.value);
    this.updatedCustomer.emit(this.customer);
    this.showView.emit('list');

  }

  onDeleteCustomer() {

    this.customerId.emit(this.customer.$key);
    this.showView.emit('list');


  }

  goBack() {

    this.showView.emit('list');

  }

}

Upvotes: 1

Views: 847

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You can set the values by iterating the data you have in customer.addresses and by the way, you can shorten the setting of values, instead of setting each value separate, you can make it shorter like:

ngOnChanges() {
  if (this.customer) {
    // set values in customerForm
    this.customerForm.setValue({
      name: this.customer.name,
      overview: this.customer.overview;
      imagePath: this.customer.imagePath
    })
    // set controls to addressForm, formArray
    let control = <FormArray>this.addressForm.get('addressGroups');
    this.customer.addresses.forEach(x => {
       control.push(this.fb.group({...}))
    })
  }
}

Notice the this.fb.group({...}) I'm not sure what form controls you have there, so you need to append them... Something like:

this.fb.group({myFormControlName1: x.myProperty1, myFormControlName2: x.myProperty2....})

Upvotes: 2

Related Questions