我在NGRX的组件库中寻找我的模型的更新单字段。
export interface MyModelState {
model: MyModel;
}
@Injectable({
providedIn: 'root'
})
export class MyModelStoreService extends ComponentStore<MyModelState> {
constructor() {
// the initial state could contain an empty model
super({ model: null });
}
readonly model$: Observable<MyModel> = this.select(state => state.model);
readonly updateModel = this.updater( (state, newModel: MyModel) => ({ ...state, model: newModel }) );
}
组件函数更新模型中的值:
updateModel(key, value) {
this.MyModelStoreService.patchState((state) => { ...state, model: { ...state, key: value } });
}
查看
<div *ngIf="myModel$ | async as myModel">
<div *ngIf="myModel.constructor.name==='First'">
<input type="number" [(ngModel)]="myModel.value" (ngModelChange)="updateModel('key', $event)" /><br />
</div>
<div *ngIf="myModel.constructor.name==='Second'">
<!-- same for other models type -->
</div>
</div>
我知道这个例子不能工作(updateModel方法),但我可以用一种适当的方式来做这件事?