使用 controlContainer 尝试复合表单
parent.component.ts
this.studentForm = new FormGroup({
'studentName': new FormControl(''),
'stateId': new FormControl(''),
'countryId': new FormControl('')
})
parent.component.html
<form [formGroup]="studentForm" (ngSubmit)="onSubmit()">
<label>Student Name:</label>
<input formControlName="studentName">
<br/><br/>
<app-country-state></app-country-state>
<br/><br/>
<button type="submit">SAVE</button>
</form>
子组件内部提供ViewContainer获取父组控制
import { Component, OnInit } from '@angular/core';
import { Country } from '../country';
import { State } from '../state';
import { SelectService } from '../select.service';
import { FormControl, FormGroupDirective, FormGroup, ControlContainer } from '@angular/forms';
@Component({
selector: 'app-country-state',
templateUrl: './country-state.component.html',
styleUrls: ['./country-state.component.css'],
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class CountryStateComponent implements OnInit {
countryId;
countryState: FormGroup;
countries: Country[];
states: State[];
constructor(private selectService: SelectService, private parentcontrol: FormGroupDirective) { }
ngOnInit() {
this.countryState = this.parentcontrol.control;
this.parentcontrol.control.updateValueAndValidity();
// this.parentcontrol.control.addControl('stateId', new FormControl(''));
this.countries = this.selectService.getCountries();
}
onSelect(countryid) {
// this.states = this.selectService.getStates().filter((item) => item.countryid == this.studentForm.controls.countryId.value);
}
}
示例:https://stackblitz.com/edit/angular-guqxbh