0

I am new to angular or front-end development for that matter. I am trying to two-way bind a form value to a 'nested array fields' of angular model. Unfortunately, it doesn't work and returns undefined or errors. Certainly looks like a blunder to me, please advice on a fix.

Code as follows,

customer.model.ts

export class Customer {
customerID:String;
customerName:String;
contract:Contract[];
}

export class Contract{
    customerID: String;
    startDate: Date;
    endDate:  Date ;
    conditions: String;
    price: Number;
    author: String; 
}

customer.component.ts

//Package imports
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

//local imports
import { CustomerService } from '../shared/customer.service';
import { Contract,Customer } from '../shared/customer.model';

declare var M: any;

@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css'],
  providers: [CustomerService]
})
export class CustomerComponent implements OnInit {

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form) {
      form.reset();

      this.customerService.selectedCustomer = {

        customerID: "",
        customerName: "",
        contract: [
          {
            customerID: "",
            startDate: null,
            endDate: null,
            conditions: "",
            price: null,
            author: ""
          }
        ]
      }
    }
  }

  onSubmit(form: NgForm) {

    this.customerService.postCustomer(form.value).subscribe((res) => {
      this.resetForm(form);
       M.toast({ html: 'Saved successfully', classes: 'rounded' });
    });


  }


}

customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Operatoroperator';


import { Customer,Contract } from './customer.model';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
  providedIn: 'root'
})
export class CustomerService {
  selectedCustomer: Customer|{}={};
   customers: Customer[];

  readonly baseURL = 'http://localhost:3000/customers';

  constructor(private http: HttpClient) { }

  postCustomer(cust: Customer) {
    console.log('front end cust value' + cust + '---' + cust.contract + '----' + cust.customerID + '----' + cust.customerName);
    return this.http.post(this.baseURL, cust);
  }


}

customer.component.html (only snippet)

Option 1 :

<input type="text" name="startDate" #name="ngModel" [(ngModel)]="customerService.selectedCustomer.contract.startDate"
                      placeholder="Enter Contract Start Date">

Option 2 :

<input type="text" name="startDate" #name="ngModel" [(ngModel)]="customerService.selectedCustomer.contract[0].startDate"
                          placeholder="Enter Contract Start Date">

Option 3 :

<input type="text" name="startDate" #name="ngModel" [(ngModel)]="customerService.selectedCustomer.contract[].startDate"
                          placeholder="Enter Contract Start Date">

Option 4:

<input type="text" name="startDate" #name="ngModel" [(ngModel)]="customerService.selectedCustomer.contract[startDate]"
                      placeholder="Enter Contract Start Date">
AshV
  • 1
  • @Silvermind I tried but returns the following error : _Uncaught Error: Template parse errors: Parser Error: The '?.' operator cannot be used in the assignment at column 58 in [customerService.selectedCustomer?.contract[0]?.startDate=$event] in ng:///AppModule/CustomerComponent.html@34:72_ – AshV Oct 10 '18 at 13:37
  • Then you would have to use an `ngIf`. – Silvermind Oct 10 '18 at 14:05
  • You should bind to an instance of `Customer` that is local to your component. Also you have an array of `Contracts` that is giving you problems, which means you will need to use *NgFor to create a set of inputs that binds to each element in that array. – DavidZ Oct 10 '18 at 14:10
  • You have a lot going on here and it is a little hard for me to follow because there are a lot of things that I don't think are right. You should have a `getCustomer()` function in your **customer.service** file. You shouldn't have a `selectedCustomer` object in your **customer.service**, and instead put it in your **customer.component**. It looks like you never populate your `customerService.selectedCustomer` object, so of course it is going to give you undefined errors. In your html, **option 2** is the closest thing you have to being correct. – rhavelka Oct 10 '18 at 16:19
  • Plus you have a random `ngForm` as an argument, but you don't have a `FormBuilder`, `FromGroup`, or `FormControl`. Also, you are using an `[(ngModel)]` instead of a `[formGroup]`. I would take a step back, and do it in chunks. First verify your data populating correctly, then display it in the ui, then put it into a form. – rhavelka Oct 10 '18 at 16:24

0 Answers0