[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>

原文地址:https://www.cnblogs.com/Answer1215/p/9775753.html

时间: 2024-08-29 12:50:30

[Angular] Expose Angular Component Logic Using State Reducers的相关文章

angular.isArray,angular.isDate,angular.isDefined,angular.isElement,angular.isFunction,angular.isNumber,angular.isObject,angular.isString,angular.isUndefined

//angular.isArray是否是数组console.log(angular.isArray([])); //trueconsole.log(angular.isArray([1,2,1,3])); //true//angular.isDate是否是日期console.log(angular.isDate('2012-12-02')); //falseconsole.log(angular.isDate(new Date)); //true//angular.isDefined引用对象是否

[Angular 2] Passing Template Input Values to Reducers

Angular 2 allows you to pass values from inputs simply by referencing them in the template and passing them into your Subject.next() call. This lesson shows you how to make a number input and pass the value so you can configure how much you want the

[AngularJS] Exploring the Angular 1.5 .component() method

Angualr 1.4: .directive('counter', function counter() { return { scope: {}, restrict: 'EA', transclude: true, bindToController: { count: '=' }, controller: function () { function increment() { this.count++; } function decrement() { this.count--; } th

[Angular 2] Exposing component properties to the template

Showing you how you can expose properties on your Controller to access them using #refs inside of your template. // letterSelect.ts import {Component, View, FORM_DIRECTIVES, NgFor} from 'angular2/angular2'; @Component({ selector: 'letter-select' }) @

angular的uiRouter服务学习(5) --- $state.includes()方法

$state.includes方法用于判断当前激活状态是否是指定的状态或者是指定状态的子状态. $state.includes(stateOrName,params,options) $state.includes方法接受三个参数,其中第二和第三个都不知道是干啥的...估计也不太用得到,就暂时不管了... stateOrName:字符串(必填). 是一个状态的名字. 比如当前的激活状态是 "contacts.details.item" 如下调用: $state.includes(&qu

[Angular 2] Angular 2 Smart Components vs Presentation Components

Both Smart Components and Presentation Components receive data from Services in entirely different ways. Smart Components use constructor injection to lookup the entire service from the injector while Angular 2 Presentation components take the data f

简话Angular 02 Angular控制器-作用域嵌套

1. html代码 <div ng-controller="ParentController"> <h3><strong>父控制器</strong></h3> <label>姓名: </label> <input type="text" ng-model='person.name'> <label>年龄: </label> {{person.age

简话Angular 07 Angular config-run-service-factory-provider-constant-value

一句话: 它们Angular框架声明周期的各个阶段,常规约定各专注于特定功能,经过处理也可以互相替换 1.功能细分简解 config Angular module模块的加载阶段-应用在此时还没有启动 run Angular应用是第一个被运行的方法,相当于其它语言中的main()方法 factory factory() 方法是创建和配置服务的最快捷方式,单例对象,在应用的生命周期内只会被调用一次注入factory,相当于注入factory定义时的函数调用入口.用 Factory 就是创建一个对象,

Angular - - ngRoute Angular自带的路由

ngRoute $routeProvider 配置路由的时候使用. 方法: when(path,route); 在$route服务里添加一个新的路由. path:该路由的路径. route:路由映射信息. controller:字符串或函数,指定控制器. controllerAs:一个用于控制器的标识符名称.. template:字符串或函数,html模板. templateUrl:字符串或函数,html模板的地址. resolve:对象,一个应该注入控制器的可选的映射依赖关系.如果任何一个依赖