改进@eliran-eliassy 答案和@christian-steinmeyer 问题。
父组件.ts
export class ParentComponent implements OnInit {
isLinear = true;
companyInfo: FormGroup;
constructor(private _formBuilder: FormBuilder) {
}
ngOnInit() {
this.companyInfo = this._formBuilder.group({
});
}
}
父组件.html
<mat-horizontal-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="companyInfo">
<form [formGroup]="companyInfo">
<ng-template matStepLabel>Fill out your name</ng-template>
<app-company-info></app-company-info>
</form>
<div>
<button mat-button matStepperNext>Next</button>
</div>
</mat-step>
</mat-horizontal-stepper>
Child.Component.ts -> 这是子表单
export class ChildComponent implements OnInit {
form: FormGroup;
subForm: FormGroup;
constructor(
private ctrlContainer: FormGroupDirective,
private fb: FormBuilder
) {}
ngOnInit() {
this.subForm = this.fb.group({
companyName: [null, [Validators.required]],
numOfEmployees: [null, [Validators.required]]
});
this.form = this.ctrlContainer.form;
this.form.addControl("company", this.subForm);
}
}
Child.Component.html
<div [formGroup]="subForm">
<mat-form-field appearance="outline">
<input matInput placeholder="Your Company Name" formControlName="companyName">
</mat-form-field>
</div>
在stackblitz上查看此解决方案