在 FormGroup 中使用 [(ngModel)]

Use of [(ngModel)] within FormGroup

我的申请中有一张注册表。但是在这个注册表中有一个可选的 'password' 和 'repeat password' 输入。因为我不想使用 FormControl 对象来检索这两个值(其他值也可以),所以我想要一个在 <form>[=15 中使用 ngModel 的解决方法=]


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>

此页面通过选择器作为子页面显示在多个页面上。将密码放在表单之外的顶部将是最懒惰的解决方案,但我必须更改一些代码才能获得它。 (加上它看起来不太好)所以我想知道是否有针对这个特定问题的解决方法。

您基本上可以指定您使用的 ngModel 是独立的。并使用类似这样的东西

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

如果您提供属性:

formControlName = "your form control name here"

在输入中它们可以像这样共存;

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

formControlName 必须与 FormGroup 中提供的名称相匹配

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