'ngSubmit not working (Following Traversy Media Angular Crash Course)
My ngSubmit is not working. The problem is that I am trying to follow Angular Crash Course this tutorial at 1:30:00 mark he tries to add in onSubmit alert and I don't get the alert, because onSubmit is not getting called so I am assuming [(ngSubmit)] is the problem. Also in add-task.component.ts I can't access this.day and this.reminder for somereason
The tutorial is outdated, it is using angular 11 and the one I downloaded angular 13 so I have to add in extra ? and ! for some reason.
Here is the HTML
add-task.component.html
<form class="add-form" (ngSubmit)="onSubmit()">
<div class="form-control">
<label for="text">Task</label>
<input
type="text"
name="text"
[(ngModel)]="text"
id="text"
placeholder="Add Task"
/>
</div>
<div class="form-control">
<label for="day">Day & Time</label>
<input
type="text"
name="day"
[(ngModel)]="day"
id="day"
placeholder="Add Day & Time"
/>
</div>
<div class="form-control form-control-check">
<label for="reminder">Set Reminder</label>
<input
type="checkbox"
name="reminder"
[(ngModel)]="reminder"
id="reminder"
/>
</div>
<input type="submit" value="Save Task" class="btn btn-block" />
</form>
add-task.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Task } from 'src/Task';
@Component({
selector: 'app-add-task',
templateUrl: './add-task.component.html',
styleUrls: ['./add-task.component.css']
})
export class AddTaskComponent implements OnInit {
@Output() onAddTask: EventEmitter<Task> = new EventEmitter();
text?: string;
day?: string;
reminder: boolean = false;
constructor() { }
ngOnInit(): void {
}
onSubmit() {
if (!this.text) {
alert('Please add a task!');
return;
}
const newTask: Task = {
text: this.text,
day: this.day,
reminder: this.reminder,
};
this.onAddTask.emit(newTask);
this.text = '';
this.day = '';
this.reminder = false;
}
}
I read some previous questions and they all say that you also have to add type submit in your button and my button is type submit so I am not sure.
I am not getting alert in onSubmit() and I can't access this.day
Solution 1:[1]
Recently I had a similar problem - couldn't spy for the call of onSubmit(), when clicking the submit button. The solution was:
Rename your "onSubmit()" function to something else like "submit()". Angular Forms use a function with this name internally and this causes trouble.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | noVaSon |