可以创建由公共字段组成的公共组件,并调用公共窗体的选择器。
DEMO
common-form.component.html格式:
<div [formGroup]="basicForm">
<mat-form-field>
<input matInput placeholder="First Name" formControlName="firstName">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Middle Name" formControlName="middleName">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Last Name" formControlName="lastName">
</mat-form-field>
</div>
通用格式.component.ts:
@Component({
selector: 'app-basic-details',
templateUrl: './basic-details.component.html',
styleUrls: ['./basic-details.component.scss']
})
@Input() basicFormGroup: FormGroup;
parent.component.html(父组件):
<form [formGroup]="form" (ngSubmit)="save()">
<app-basic-details [basicForm]="form"></app-basic-details>
<mat-form-field>
<input placeholder="age" matInput formControlName="age">
</mat-form-field>
<mat-form-field>
<input placeholder="Class" matInput formControlName="className">
</mat-form-field>
<button mat-raised-button type="submit" color="primary">Save</button>
</form>
<div>
{{form.value | json}}
</div>
父.component.ts:
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
age: null,
className: null,
firstName: null,
middleName: null,
lastName: null
})
}
save(){
console.log(this.form.value)
}