import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'app-reactived-form',
templateUrl: './reactived-form.component.html',
styleUrls: ['./reactived-form.component.css']
})
export class ReactivedFormComponent implements OnInit {
public formModel: FormGroup;
public fb: FormBuilder = new FormBuilder();
constructor() {
/* this.formModel = this.fb.group({
nickName: [''],
emails: this.fb.array([['']]),
passwordInfo: this.fb.group({
password: [''],
passwordConfirm: ['']
})
});*/
this.formModel = new FormGroup({
nickName: new FormControl(),
emails: new FormArray([new FormControl(), new FormControl()]),
passwordInfo: new FormGroup({
password: new FormControl(),
passwordConfirm: new FormControl()
}
)
});
}
createUser() {
let n = this.formModel.get('nickName') as FormControl;
console.log(n.value);
}
addEmail() {
let emails = this.formModel.get('emails') as FormArray;
emails.push(new FormControl());
console.log(this.formModel.value);
}
ngOnInit() {
}
}
<form [formGroup]="formModel" (submit)="createUser()">
<div>昵称:<input formControlName="nickName" pattern="[a-zA-Z0-9]"></div>
<div>邮箱:
<ul formArrayName="emails">
<li *ngFor="let email of formModel.get('emails').controls; let i= index">
<input [formControlName]="i">
</li>
</ul>
<button (click)="addEmail()">添加email</button></div>
<div [formGroup]="formModel.get('passwordInfo')">
<div>密码:<input formControlName="password" type="password"></div>
<div>确认密码:<input formControlName="passwordConfirm" type="password"></div>
</div>
<div>
<button type="submit">注册</button>
</div>
</form>
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-template-form',
templateUrl: './template-form.component.html',
styleUrls: ['./template-form.component.css']
})
export class TemplateFormComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
createUser(values) {
console.log('createUser');
}
}
<form #myForm="ngForm" (ngSubmit)="createUser(myForm.value)">
<div>昵称:<input ngModel name="nickname" pattern="[a-zA-Z0-9]"></div>
<div>邮箱:<input ngModel name="email" type="email"></div>
<div ngModelGroup="passwordInfo">
<div>密码:<input ngModel name="password" type="password"></div>
<div>确认密码:<input ngModel name="password" type="password"></div>
</div>
<div><button type="submit">注册</button></div>
</form>