angulartypescriptangular-template-form

Create a template based form in Angular


I tried to create a form in Angular but I have some issues when I want to access values from the form in my component.

My form looks like this:

<div class="col-md-6">
  <form #createTaskForm="ngForm" (ngSubmit)="saveTask(createTaskForm.value)" autocomplete="off" novalidate>
    <div class="form-group">
      <label for="taskDescription">Task Description:</label>
      <input [(ngModel)]="task.description" name="taskDescription" required id="taskDescription" type="text" class="form-control" placeholder="Description..." />
    </div>
    <div class="form-group">
      <label for="taskDate">Date:</label>
      <input [(ngModel)]="task.date" name="taskDate" required id="taskDate" type="text" class="form-control" placeholder="(mm/dd/yyyy)..." />
    </div>

    <button type="submit" class="btn btn-primary">Save</button>
    <button type="button" class="btn btn-success" (click)="cancel()">Cancel</button>
  </form>
</div>

And this is the component:

export class CreateTaskComponent implements OnInit {

  task: Task;

  constructor(
    private router: Router,
    private taskService: TaskService) { }

  ngOnInit() {
  }

  saveTask(valuesFromForm) {
    console.log(valuesFromForm);
    this.taskService.save(valuesFromForm);
    this.router.navigate(['/tasks']);
  }

  cancel() {
    this.router.navigate(['/tasks']);
  }
}

And I receive this error when I want to see the values from form:

ERROR TypeError: Cannot read property 'description' of undefined

Solution

  • this a JavaScript error rather than angular error , simplify any property don't have a value it 's considered a undefined and access to property of undefined value will rise this error.

    ERROR TypeError: Cannot read property 'description' of undefined
    

    to solve thing just initialize your property with instance of Task class

    task: Task = new Task()