首先我不会遵守三个独立的数字,而是创造一些包装器它(让我们暂时称之为wrapper
- 记住从休息电话你应该收到一个领域的对象)
export class Wrapper {
districtId: number;
municipalityId: number;
settlementId: number;
constructor(dist, mun, sett){
this.districtId = dist;
this.municipalityId = mun;
this.settlementId = sett;
}
}
那么我们app.html看起来像:
District id: {{ wrapper.districtId }}
Minicipality id: {{ wrapper.municipalityId }}
Settlement id: {{ wrapper.settlementId }}
<my-child [wrapper]="wrapper"></my-child>
说明该领域的每一次变化都会自动在wrapper.districtId
等
可见,我们可以简化我们的子组件: 当我们输入我们不能将我们的逻辑基于OnChanges()(因为它会被称为一旦对象变化引用了wrapper
,在我们的例子中只有字段被更新),但是我们可以调用select
上的特定函数变化:
<div>
<label for="district">District</label>
<select id="district" (change)="setMunicipalities()" [(ngModel)]="wrapper.districtId">
<option [value]="district.id" *ngFor="let district of districts">{{ district.name }}</option>
</select>
</div>
和最终逻辑。请注意,当我们调用setMunicipalities()我们并不需要检查是否有任何改变,请注意,我们没有额外的检查有什么改变(如前)
constructor(private changeDetector: ChangeDetectorRef) {
this.districts = DISTRICTS;
}
ngOnInit() {
this.setMunicipalities();
this.setSettlements();
}
private setMunicipalities() {
this.municipalities = MUNICIPALITIES.filter(mun => mun.districtId == this.wrapper.districtId);
this.setSettlements();
this.changeDetector.detectChanges();
}
private setSettlements(){
this.settlements = SETTLEMENTS.filter(sett => sett.municipalityId == this.wrapper.municipalityId);
}
我叉你plunker(https://plnkr.co/edit/A7aGJcZhQAryvVPLTrOA?p=preview) - 我有在plunker中注入ChangeDetectorRef的问题(所以不是所有的下拉列表都会自动更新,但希望你有这种感觉)
我不知道Reactive Forms的细节,但这是一个有趣的例子。 –