我有一个带有<select>
形式的组件。表单下方是一个具有特定布局的空表,在子组件中实现。
当前在组件初始化期间(getFamilies
)从REST API获取可用项列表。对于子组件而言,selectedFamily
是一个对象而不仅仅是一个字符串是很重要的。
选择后,我使用router.navigate
更新路线,以便用户可以为该页面添加书签/共享。
目前,我使用router.params
“回调”在单独的变量selectedFamilyName
中手动记录姓氏,并在从服务加载列表时使用它来查找系列对象:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Family } from './family';
import { FamilyService } from './family.service';
import { FamilyTable } from './family-table.component';
@Component({
template: `
<div class="form-group">
<select [(ngModel)]="selectedFamily" (ngModelChange)="onSelect($event)"
class="form-control">
<option *ngFor="let family of families" [ngValue]="family">
{{ family.name }}
</option>
</select>
</div>
<familytable [family]=selectedFamily></familytable>
`,
directives: [FamilyTable],
})
export class FamilyList implements OnInit, OnDestroy {
errorMessage: string;
families: Family[] = [];
selectedFamily: Family;
selectedFamilyString: string = "";
private _sub: any;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _familyService: FamilyService) { }
ngOnInit() {
this.getFamilies();
this._sub = this._route.params.subscribe(params => {
// record the family string for list item selection
this.selectedFamilyString = params['family'];
});
}
ngOnDestroy() {
this._sub.unsubscribe();
}
getFamilies() {
this._familyService.getFamilies().subscribe(
families => {
this.families = families;
this.selectedFamily = this.families.find(family => family.name === this.selectedFamilyString);
},
error => this.errorMessage = <any>error,
);
}
onSelect(family: Family) {
this._router.navigate(['families', family.name]);
}
}
这种手动簿记感觉很麻烦。是否有更好,更优雅甚至推荐的方法来做这类事情?