Reputation: 10230
I have created the following angular component:
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'weather-search',
template: `
<section>
<form (ngSubmit)="onSubmit(f)" let f="ngForm" class="search__form">
<label for="search_city">Enter City</label>
<input ngControl="location" type="text" id="search_city" placeholder="Enter City" required/>
<button type="submit">Add City</button>
</form>
<div class="locationsearch__info">
<span class="info">City Found</span>:<span>Kansas</span>
</div>
</section>
`,
styleUrls: ['./weather-search.component.css']
})
export class WeatherSearchComponent {
onSubmit(form: FormGroup) {
console.log(form);
}
}
I am using this component in my app.component.ts like so:
@Component({
selector: 'app-root',
template: `
<weather-search></weather-search>
<weather-list></weather-list>
`,
styleUrls: ['app.component.css']
})
Now the thing is when i click on submit i expect that the submit will be stopped and the form data will be console.log
'ed, thats not whats happening right now , just to give a brief preview of my code, notice how i have a local variable let f="ngForm"
and on submit i am passing this variable to the submit handler like so (ngSubmit)="onSubmit(f)"
.
As of now though on submit i see nothing in the console. Why is my submit handler not working ?
Upvotes: 0
Views: 488
Reputation: 11184
Try like this :
template :
<form name="f" (ngSubmit)="onSubmit(f)" #f="ngForm" class="search__form"></form>
typescript :
import { NgForm } from '@angular/forms';
export class HomeComponent {
onSubmit(f: NgForm) {
console.log('f', f);
}
}
Upvotes: 1
Reputation: 435
You have to use # symbol to define a local variable like this in your case:
<form (ngSubmit)="onSubmit(f)" #f="ngForm" class="search__form">
Upvotes: 2