其他分享
首页 > 其他分享> > angular7响应式表单基本使用

angular7响应式表单基本使用

作者:互联网

案例1:

**使用响应式表单需要在app.module.ts中引入ReactiveFormsModule **

import { ReactiveFormsModule } from '@angular/forms';

<form [formGroup]="formModel" (ngSubmit)="onSubmit()">
    <div formGroupName="dateRange">
        起止日期:<input type="date" formControlName="from"> <br>
        截止日期:<input type="date" formControlName="to">
    </div>
    <div>
        <ul formArrayName="emails">
            <li *ngFor="let item of this.formModel.get('emails').controls; let i = index;">
                <input type="text" [formControlName]="i">
            </li>
        </ul>
        <button (click)="adEmail()">增加email</button>
    </div>
    <button type="submit">保存</button>
</form>
export class Form3Component implements OnInit {

    formModel: FormGroup = new FormGroup({
        dateRange: new FormGroup({
            from: new FormControl(),
            to: new FormControl()
        }),
        emails: new FormArray([
            new FormControl('a@a.com'),
            new FormControl('b@b.com')
        ])
    });

    constructor() { }

    ngOnInit() {
    }

    onSubmit() {
        console.log(this.formModel.value);
    }

    adEmail() {
        let emails = this.formModel.get('emails') as FormArray;
        emails.push(new FormControl(''));
    }

}

案例2

<form [formGroup]="formModel" (ngSubmit)="onSubmit()">
    <div>
        用户名:<input type="text" formControlName="username">
    </div>
    <div>
        手机号:<input type="number" formControlName="mobile">
    </div>
    <div formGroupName="passwordsGroup">
        <div>
            密码:<input type="password" formControlName="password">
        </div>
        <div>
            确认密码:<input type="password" formControlName="pconfirm">
        </div>
    </div>
    <button>注册</button>
</form>
formModel: FormGroup;

constructor() {
    this.formModel = new FormGroup({
        username: new FormControl(),
        mobile: new FormControl(),
        passwordsGroup: new FormGroup({
            password: new FormControl(),
            pconfirm: new FormControl()
        })
    });
}

ngOnInit() {
}

onSubmit() {
    console.log(this.formModel.value);
}

案例3

使用formBuilder简写响应式表单

constructor(private fb: FormBuilder) { }

 formModel = this.fb.group({
     username: [''],
     mobile: [''],
     passwordsGroup: this.fb.group({
         password: [''],
         pconfirm: ['']
     })
 });

 ngOnInit() {
 }

 onSubmit() {
     console.log(this.formModel.value);
 }

标签:FormControl,响应,formModel,表单,ngOnInit,angular7,new,FormGroup,emails
来源: https://blog.csdn.net/yw00yw/article/details/90238330