我尝试在 Angular 中创建一个表单,但是当我想从组件中的表单访问值时遇到了一些问题。
我的表格如下所示:
<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>
这是组件:
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']);
}
}
当我想查看表单中的值时,我会收到此错误:
ERROR TypeError: Cannot read property 'description' of undefined