加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

[Angular] Expose Angular Component Logic Using State Reducer

发布时间:2020-12-17 07:05:02 所属栏目:安全 来源:网络整理
导读: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 overrid

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读