Магазин Angular 2 Ngrx: Обновление массива

В настоящее время у меня есть приложение angular2 CRM, основанное на архитектуре ngrx/store. У меня есть функции CRUD для обновления, перечисления и добавления клиентов, которые работают нормально, и все они связаны с базой данных Firebase с помощью ngrx / Effects.

Чтобы синхронизировать смарт-компонент с магазином, у меня есть следующий код. Опять все работает нормально, однако я не уверен, как обновить массив в форме - см. Код ниже: -

Здесь я обновляю форму данными из магазина

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);

        }

Я хочу сделать то же самое с адресной формой, но не знаю, как это сделать, чтобы заполнить объект массива в форме. Любые идеи / предложения приветствуются

Когда я регистрирую консоль ниже, у меня фактически есть детали адреса, просто нужно знать, как получить их в объекте формы.

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"

Полная информация о клиенте 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');

  }

}

1 ответ

Решение

Вы можете установить значения, повторяя данные, которые у вас есть в customer.addresses и, кстати, вы можете сократить установку значений, вместо того, чтобы устанавливать каждое значение отдельно, вы можете сделать его короче, например:

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({...}))
    })
  }
}

Обратите внимание на this.fb.group({...}) Я не уверен, какие формы управления у вас там, поэтому вам нужно добавить их... Что-то вроде:

this.fb.group({myFormControlName1: x.myProperty1, myFormControlName2: x.myProperty2....})
Другие вопросы по тегам