Search code examples
angulartypescriptangular2-templateangular2-formsangular2-services

why are values in object updated on submit


Every Time a user submits the form, the data related to that task gets stored in an object and that object gets passed into an array which holds list of tasks.

Image to the console error

Now when you log the tasksList array to console. each task gets the same value of "date". Values for all the instance of a tasks are overwritten. I want the object to have seperate values of "date" for each person.

// app component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { ITaskDetails } from './interfaces/task-details';
import { TaskService } from './services/task.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  currentDate: {};
  taskForm: FormGroup;
  taskArr: ITaskDetails[];
  taskObj: ITaskDetails = {
    title: '',
    description: '',
    date: null
  };

  constructor(private taskSer: TaskService) {
    this.currentDate = new Date().toISOString().substring(0, 10);
  }
  ngOnInit() {
    this.taskForm = new FormGroup({
      'taskTitle': new FormControl(''),
      'description': new FormControl(''),
      'date': new FormControl(this.currentDate)
    });
    console.log(this.taskForm);
  }

  onSubmit() {
    this.taskObj.title = this.taskForm.get('taskTitle').value;
    this.taskObj.description = this.taskForm.get('description').value;
    this.taskObj.date = this.taskForm.get('date').value;

    console.log(this.taskObj);

    this.taskSer.setData({...this.taskObj});
    this.taskArr = this.taskSer.getdata();
    console.log(this.taskArr);
  }
}

// Task Service

import { Injectable } from '@angular/core';
import { ITaskDetails } from '../interfaces/task-details';

@Injectable()
export class TaskService {
  taskArr: ITaskDetails[] = [];
  taskDetails = {
    title: '',
    description: '',
    date: null
  };

  setData(obj: ITaskDetails) {
    this.taskDetails.title = obj.title;
    this.taskDetails.description = obj.description;
    this.taskDetails.date = obj.date;
    this.taskArr.push(this.taskDetails);
  }
  getdata() {
    return this.taskArr;
  }
  constructor() { }

}

// form template

<section class="container">
  <div class="panel panel-default">
    <div class="panel-heading">Add a Task</div>
    <div class="panel-body">
      <form class="form-horizontal" [formGroup]="taskForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="title" class="col-sm-2 control-label">Title *</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="taskTitle" placeholder="Title of Task" formControlName="taskTitle">
          </div>
        </div>
        <div class="form-group">
          <label for="description" class="col-sm-2 control-label">Description *</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="description" placeholder="Enter Your Description" formControlName="description">
          </div>
        </div>
        <div class="form-group">
          <label for="date" class="col-sm-2 control-label">Date of Completion *</label>
          <div class="col-sm-10">
            <input type="date" class="form-control" id="date" formControlName="date">
          </div>
        </div>
        <div class="form-group">
          <div class="col-md-offset-6">
            <button type="submit" class="btn btn-default" [disabled]="!taskForm.valid">Submit your data</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</section>
<section class="container">
  <app-task-list></app-task-list>
</section>

Solution

  • you need to spread your taskDetails object in your service method like this

    setData(obj: ITaskDetails) {
        this.taskDetails.title = obj.title;
        this.taskDetails.description = obj.description;
        this.taskDetails.date = obj.date;
        this.taskArr.push({...this.taskDetails}); <<<<<this
    }
    

    not when you are calling the method and passing the object. Remove the spread object form

    onSubmit() {
        this.taskObj.title = this.taskForm.get('taskTitle').value;
        this.taskObj.description = this.taskForm.get('description').value;
        this.taskObj.date = this.taskForm.get('date').value;
    
        console.log(this.taskObj);
    
        this.taskSer.setData({...this.taskObj}); <<<<this to setData(this.taskObj);
        this.taskArr = this.taskSer.getdata();
        console.log(this.taskArr);
    }