Redux and mat-selection-list in Angular

Redux and mat-selection-list in Angular

In this post, we look at a couple pieces of code that can help Angular developers better understand the framework and working with TypeScript.

In this post, we look at a couple pieces of code that can help Angular developers better understand the framework and working with TypeScript.

How to Install Redux Dev Tools in Angular 6
  1. Install Redux Dev Tools from the Chrom web store.
  2. Install ngrx dev tools in your Angular project:
npm install @ngrx/[email protected] --save

3. Add the ngrx dev tools module to your project:

import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment'; // Angular CLI environemnt

@NgModule({
  imports: [
    StoreModule.forRoot(reducers),
    // Instrumentation must be imported after importing StoreModule (config is optional)
    StoreDevtoolsModule.instrument({
      maxAge: 25, // Retains last 25 states
      logOnly: environment.production, // Restrict extension to log-only mode
    }),
  ],
})
export class AppModule {}

mat-selection-list for select all checkbox in Angular 6

HTML with inline tutorial:

 <mat-selection-list formControlName="areasCtrl" role="list">
   <!-- add select all option here and add select all event -->
      <mat-list-option #areaSelectAll value="ALL" (click)="areaSelectAllEvent()" aria-label="select all">Select All</mat-list-option>
      <mat-list-option *ngFor="let area of areaArray" [value]="area.areaName" aria-label="{{area.areaFullName}}">
        {{area.areaFullName}}
      </mat-list-option>
 </mat-selection-list>

Component part (TypeScript code with tutorial notes given in the comments):

/*
select all event for select all option

areaSelectAllEvent is used to reset areasCtrl formcontrol with all the list of value
or with empty list of value

*/
areaSelectAllEvent(){
    if(this.areaSelectAll.selected){
      let allList = this.getAreaValueFromList(this.areaArray);
         allList.unshift('ALL');
      console.log(allList);
      this.spForm.get('areasCtrl').setValue(allList, {emitEvent: false});
      this.selAreas = allList; 
  }else{
      this.spForm.get('areasCtrl').setValue([]);
  }
 }

/*
value changes for area form contontrol

*/
this.spForm.get('areasCtrl').valueChanges.subscribe(areas =>{

      //add feature for select all if selecte all is set, check other option will reset the select all
      let area = areas;
      if(area.includes('ALL') && area.length > 1  && area.length < this.areaArray.length+1){        

        const dif = _.difference(area,this.selAreas); //compare current value with previous value
          if(dif[0] !== 'ALL'){
            area.shift(); // remvoe all from array
            this.spForm.get('areasCtrl').setValue(area);
          }         
      }

      this.selAreas=areas;
    })

Why you should NEVER use Redux with Angular

Why you should NEVER use Redux with Angular

While Redux solved a lot of problems with React, it’s use case doesn’t apply to Angular. Why?

Originally published by https://www.stackchief.com
Preface: What is Redux?

Redux is a JavaScript library for managing application state. It was popularized by React because it solved the "extraneous props" issue and played well with flux architecture.

What is the extraneous props issue?

Like Angular, React generates UI components that fall within a “component hierarchy”. Parent components can pass data to child components by way of props. This is similar to how the @Input decorator works in Angular.

While this makes it possible for components to share data, it gets messy when you want to pass data 5-10 levels up or down the component tree. Components end up having “extraneous properties” that create unnecessary relationships with other components. This makes them less reusable.

What is Flux?

Flux is a design pattern popularized by React. It emphasizes unidirectional data flow and proved more performant than the two-way data binding popularized by AngularJS. In fact, the rewrite of Angular was largely influenced by Flux concepts.

Why You Should NOT Use Redux With Angular

While Redux solved a lot of problems with React, it’s use case doesn’t apply to Angular.

React is simply a UI component library. Angular is a highly opinionated framework around dependency injection (DI). This makes it easy to share state out of the box. Services can easily be shared across different component classes....

@Injectable()

export class AppStore {

    userName: "Sam"

    constructor() { }

}


export class Comp1 {

      constructor(store:AppStore){

          this.displayName = store.userName;

      }

}

export class Comp2 {

      constructor(store:AppStore){

          this.userName = store.userName;

      }

}

While you can achieve something similar with React, the easier option is to use Redux.

This is why Redux became so popular with React. It's the same way other third party libraries (like Axios) became popular with React. These libraries are necessary because React is simply a UI component library.

Just like Redux makes it easier to share state, Axios makes it easier to make Ajax requests.

And just like Angular doesn't need Axios because of it's own httpClientModule, it doesn't need Redux because of things like DI, services, and RxJS....

RxJS and Redux

RxJS is a library for making async requests. It leverages the observable design pattern to bring a reactive pub/sub functionality to Angular.

Using RxJS, Angular components can subscribe to event streams. This allows them to listen for data changes (events) over time.

So what does this have to do with Redux? It turns out Redux implements a similar pub/sub relationship between components and the store. Components subscribe to stores in Redux just like components subscribe to RxJS Observables in Angular.

For these reasons, you can argue that Redux is a redundant addition to Angular because Angular achieves the same behavior using RxJS.

Too Much Boilerplate

Redux works by dispatching defined "actions" that functions called "reducers" interpret to update a centralized "store". This tends to generate a lot of boilerplate code as your app grows and gets messy fast.

While Angular has its fair share of boilerplate, you don't need an excuse to add even more. Since using things like RxJS and shared services is a proven alternative, there is no need to further complicate your code base with a bunch of actions and reducers.

Conclusion

The Angular team put a lot of thought into component interaction and shared state. The framework already has everything you need to share state across different components. It's change detection strategy is super fast out of the box so don't worry about performance implications of cross-component interaction or immutability and OnPush.

Remember that Redux was an answer to React problems. And just like Angular doesn't need Axios, it doesn't need Redux...

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Building CRUD Mobile App using Ionic 4, Angular 8

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

Ionic 4 & Angular Tutorial For Beginners - Crash Course

Understanding of ngRx with Redux in Angular

Understanding of ngRx with Redux in Angular

In this post is useful for you to get the basic understanding of ngrx with redux after reading this post and you will start using it in your application

Originally published by Nitin Arora at https://blog.knoldus.com

In this post, we will see the basic pattern of Redux and some benefits and some high-level concepts of redux and then we will discuss the brief about ngRx and its basic implementation.

Redux: Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time-traveling debugger.

Redux is available as a package on NPM for use with a module bundler or in a Node application:

npm install --save redux

So let’s discuss the basic concepts of redux which are also used for Redux.


So now we will see the overall concept of redux and see hows it works. Here, we can see that we have a UI and when a user performs an action it will change the state of the data.

Here the question arrives, What is the state?

Basically, all the application data is collectively known as the store and it is to be represented as a state. Also, we cannot change the state as it is immutable. We can change the state only using Action, which itself is an object which included two things:

1: Type: Type is nothing but it is an Action Name.

2: Payload: Alternatively, Payload is something we can refer to as Action Data.

Example of Action:

{ type: ‘DELETE_ITEM’, payload: 123 }

Here, you can see that in action, Delete_Item is our action name and 123 is an action data.

So How’s it works?

1: When data changes, the existing state is duplicated, then a new object is created with the updates. In Angular this data is treated as an RxJS Observable, allowing us to subscribe to it from anywhere in the app.

2: When an event is emitted, for example, a button click, the action is sent to a reducer function to converts the old state into the new state.

NgRx: The ngRx is an angular version of the redux pattern. Which is inspired by the group of libraries inspired by flux pattern. what do I mean with “angular/rxjs” version of redux The angular part is because ngrx is a library to use within an angular application. The rxjs “part is because of the implementation of ngrx works around an rxjs flow.

How to configure ngRx?

You can set up ngRx with just 2 steps described below:

1: create one new app with Angular-CLI and give it any name to it.

ng new ngrxProject --routing
cd ngrxProject

2: Install the ngrx/store via npm in your system with the following command.

sudo npm install @ngrx/core @ngrx/store --save

Now let us understand this concept with the help of the basic example shown below:

app.module.ts

Here, in this file, we need to update the app module file with the post reducer, for that we need to import the post reducer.

import { StoreModule } from '@ngrx/store';
import { simpleReducer } from './simple.reducer';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
StoreModule.forRoot({ message: simpleReducer })
],
bootstrap: [AppComponent]
})
export class AppModule { }

ngrx.reducer.ts

Now, we will create one another file in which we create the reducer.

import { Action } from '@ngrx/store';

export function simpleReducer(statement: string = 'I am learning',
action: Action) {

switch (action.type) {

	case 'German':
	  return statement = 'Ich lerne'

           case 'FRENCH':
             return statement = 'j'apprends'

	default:
	return statement;      
}

}

So, here we have switch statements with the possible actions and this whole function is collectively known as a reducer. In this function, the switch statement returns the statement as ‘i am learning’ in different languages depending upon the actions.

app.component.ts

  • So now if we want to change the state and we will use the class store then we need to implement interface corresponding to the object necessary to pass to the ngModule.
  • A variable for message$  is set as an Observable on the component by calling this.store.select(‘message’).
  • We trigger state changes by sending actions to the reducer with this.store.dispatch (‘ACTION’).
import { Component } from '@angular/core';

import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';

interface AppState {
message: string;
}

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {

message$: Observable<string>

constructor(private store: Store) {
this.message$ = this.store.select('message')
}

germanMessage() {
this.store.dispatch({type: 'GERMAN'})
}

frenchMessage() {
this.store.dispatch({type: 'FRENCH'})
}
}

Now we can subscribe to the Observable in the HTML and trigger changes with button click events.

<h2>{{ message$ | async }}</h2>

<button (click)="GermanMessage()">German</button>
<button (click)="frenchMessage()">French</button>

Conclusion: I hope this blog is useful for you to get the basic understanding of ngrx with redux after reading this blog and you will start using it in your application.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Building CRUD Mobile App using Ionic 4, Angular 8


Angular Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch: This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

Learning Angular can be a daunting experience that's why this course was created; to give you an easier learning experience with it.

What am I going to get from this course?

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond

What you'll learn

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond