To use template driven approach to handle forms. We assign a name to the form using the NgForm directive. We then use a submit event handler, to listen to a submit event. Since our form button is of type submit, a submit event is triggered every time a user submits the form.
<form (submit)="onAddPost(postForm)" #postForm="ngForm">
<input type="text" ngModel name="title" #title="ngModel">
<textarea rows="4" ngModel name="content" #content="ngModel"></textarea>
<button type="submit"> Save Post </button>
</form>
The NgForm creates an instance of the form and binds to the form in the template. To access the forms inputs we call the form instance and its value property.
onAddPost(form: NgForm) {
console.log(form, form.value, form.value.title, form.value.content);
}
Top comments (0)