Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Angular Basics Angular Basic Forms Resetting the Form

Quinn Moreland
Quinn Moreland
2,634 Points

Why so much work to reset the form?

It's very possible that I'm missing something here, but I don't see the merit in all the work to reset the form. I feel like the following code solves the same problem, but does it without all the imports and edits to the entry-comment-form.component.html file. I have commented the two new lines. I ran it, and it works. So why such a verbose solution?

import { Component, EventEmitter, Output } from '@angular/core';

@Component({

selector: 'app-entry-comment-form',
templateUrl: 'entry-comment-form.component.html'

}) export class EntryCommentFormComponent { name: string = ""; comment: string = ""; @Output() onCommentAdded = new EventEmitter<{name: string; comment: string;}>(); onSubmit(){ let comment = { name: this.name, comment: this.comment }; this.onCommentAdded.emit(comment);

    //I feel like this should, in theory, reset the form? But treehouse wants something else
    this.name = "";
    this.comment = "";
}

}

Oziel Perez
Oziel Perez
61,321 Points

I have never used typescript, let alone Angular 2+, but from my experience with React, I would assume that what's happening here is that the Component class is modified in the background to account for the NgForm object and passes in a reference to the form when the events are triggered (similar to componentDidUpdate or some other lifecycle method in React). This exposed object allows you to call several helper methods and not have to write a bunch of code to do one thing (Ironically though, document.forms[0].reset() is a one-liner that you can use in plain javascript and is simpler compared to all this set up for angular), like validating the form and so forth.

1 Answer

Christof Baumgartner
Christof Baumgartner
20,864 Points

Hi Quinn,

I had the exact same thought and it works fine for me. This is the same approach that is used in the Vue.js course to reset the form. The [(ngModel)] is a two-way data binding, so I don't see the problem in solving it this way. However I understand that ngForm can do a lot more things, so it is not bad to have it defined in general, so maybe thats the reason why he used it. Would be nice to have an Angular Veteran comment on this and point out if the proposed solution would be good or bad practice...