Search code examples
angularangular2-form-validation

Angular template driven form validation : should I post ngModel or form.value?


This is a question about good practices with Angular 2+ template driven forms validation.

When I have

<form #form="ngForm">
    firstname : <input [(ngModel)]="user.firstname" name="firstname" />
    <button [disabled]="form.invalid" (click)="post()">Post</button>
</form>

Should I do

post() {
    this.userService.post(this.user);
}

Or

post() {
    this.userService.post(this.form.value);
}

?


Solution

  • If your entity object (user in your example) has any properties, such as an ID, that are not included on the form ...

    This code:

    post() {
        this.userService.post(this.form.value);
    }
    

    Won't include them. So it would not include the Id of the user for example.

    This code:

    post() {
        this.userService.post(this.user);
    }
    

    Will include all of the user properties.

    You can see this by defining your entity object like this:

    export interface IUser {
        id: number;
        firstname: string;
        lastname: string;
        isAdmin: boolean;
    }
    

    Add the first and last name to your form as you did above, then add the following to your post:

        console.log('form: ' + JSON.stringify(this.form.value));
        console.log('entity: ' + JSON.stringify(this.user));