[Angular] Expose Angular Component Logic Using State Reducers

來源:互聯網
上載者:User

標籤:return   class   out   ansi   ret   parent   problem   cep   get   

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>

 

 

[Angular] Expose Angular Component Logic Using State Reducers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.