Use of [(ngModel)] within FormGroup

2020-08-09 05:23发布

问题:

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.

回答1:

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}" />



回答2:

If you provide the attribute:

formControlName = "your form control name here"

in the input then they can co-exist like so;

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

The formControlName must match the name provided in your FormGroup

this.formGroup = this._formBuilder.group({
  'password': new FormControl(this.password, [
     Validators.required,
     Validators.minLength(4)
  ])
});


回答3:

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