在FormGroup中使用[(ngModel)]

Iva*_*ers 23 typescript angular2-forms angular

我在申请表上有一份登记表.但在此注册表格中,有一个可选的"密码"和"重复密码"输入.因为我宁可不使用FormControl对象来检索这些2个值(其他值都很好),我想为使用的一种解决方法ngModel中的<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]
    });
 }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

Has*_*hat 47

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

 <input type="password" [(ngModel)] = "password" [ngModelOptions]="{standalone: true}" />
Run Code Online (Sandbox Code Playgroud)