[Angular] Expose Angular Component Logic Using State Reducers
A component author has no way of knowing which state changes a consumer will want to override, but state reducers handle this problem by allowing the parent component to override any state change.
In Short, we want to have a way to override the component's internal state from outside. The reason for that is there maybe some requirements from the users who want to override component internal state for whatever reason.
The state reducer can accomplish this task, so what is state reducer? It is just a fansic name form some smart developers. State reducer is a function which two two params, one is old state, another one is changes going to be happen, return value is the new state.
export type ToggleStateReducer = (state: ToggleState, changes: Partial<ToggleState>) => ToggleState;
So inside toggle.component.ts, we accept an @Input() stateReducer:
@Input() stateReducer: ToggleStateReducer =
(state, changes) => ({ ...state, ...changes });
Whenenver we need to change toggle component internal state, we call stateReducer:
setOnState(on: boolean) { const oldState = { on: this.on }; const newState = this.stateReducer(oldState, { on }); if (oldState !== newState) { this.on = newState.on; this.toggled.emit(this.on); } }
That's all what we need to for component part. Just make stateReducer as a input, call each time we need to udpate our internal state, we call thought stateReducer to get new state.
So now, from the consumer component, we can control the state update:
// app.component.ts: stateReducer = (state: ToggleState, changes: Partial<ToggleState>) => { if (this.timesClicked > 3) { return state; } if (changes.on !== undefined) { this.timesClicked = this.timesClicked + 1; } return { ...state, ...changes }; }
<toggle (toggled)="log('toggle', $event)" [stateReducer]="stateReducer"> <ng-template let-on="on" let-fns="fns"> <switch [on]="on" toggler (click)="fns.toggle()"> </switch> </ng-template> </toggle>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-10-11 [AngularJS] Sane, scalable Angular apps are tricky, but not impossible.