Use of [(ngModel)] within FormGroup

Ivar Reukers picture Ivar Reukers · Jan 9, 2017 · Viewed 24.6k times · Source

I have in my application a registration form. But within this registration form there is an optional 'password' and 'repeat password' input. Since I'd rather not use the FormControl object to retrieve these 2 values (other values are fine), I would like a workaround for the usage of ngModel within a <form>


MCVE

TS:

public password: string = '';
public passwordRe: string = '';
public registrationForm;

constructor(public fb: Formbuilder) {
    this.registrationForm = this.fb.group({
        'firstname' : [null, Validators.required],
        'lastname': [null, Validators.required]
    });
}

HTML

<form [formGroup]="registrationForm" (ngSubmit)="doSomething()">
    <div class="form-group"
            [ngClass]="{'has-error':!registrationForm.controls['firstname'].valid 
                && registrationForm.controls['firstname'].touched}">
        <label>Firstname: *</label>
        <input class="form-control" type="text" placeholder="Firstname" [formControl]="registrationForm.controls['firstname']"/>
    </div>

    <div class="form-group"
            [ngClass]="{'has-error':!registrationForm.controls['lastname'].valid 
                && registrationForm.controls['lastname'].touched}">
        <label>Lastname: *</label>
        <input class="form-control" type="text" placeholder="Lastname" [formControl]="registrationForm.controls['lastname']"/>
    </div>

    <!-- NG MODELS -->

    <input type="password" [(ngModel)]="password"/>
    <input type="password" [(ngModel)]="passwordRe" />

    <input type="submit" value="Some submit button"/>
</form>

This page is shown on multiple pages as a child, via a selector. Placing the passwords on top, outside of the form would be the laziest solution, but I'd have to change some code to get that. (plus it doesn't look good) So I was wondering if there's a workaround for this specific issue.

Answer

Hasan Wajahat picture Hasan Wajahat · Feb 23, 2017

You can basically specify that the ngModel you are using is standalone. And use something like this

 <input type="password" [(ngModel)] = "password" [ngModelOptions]="{standalone: true}" />