Angular ChangeDetectorRef

import { JsonPipe } from '@angular/common';
import { Component, VERSION, ViewChild, AfterViewInit , AfterViewChecked, AfterContentChecked, SimpleChanges ,OnChanges, ElementRef  } from '@angular/core';
import { ChildComponent } from './child/child.component';
import { ChangeDetectorRef } from '@angular/core';
@Component({  
   selector: 'my-app',  templateUrl: './app.component.html',  
   styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, AfterViewChecked {  
constructor(private cdRef:ChangeDetectorRef) {}  
@ViewChild(ChildComponent) hello:ChildComponent;  
@ViewChild('title') title: ElementRef;  
aname = 'Ajay' 
 name = 'Angular ' + VERSION.major; 
 xx:any;  
ngAfterViewInit() {   
   this.aname = this.hello.name  
}  
ngAfterViewChecked(){    
   this.aname = this.hello.name   
   //console.log(this.title.nativeElement.innerText)    
   this.cdRef.detectChanges();  
} 
ngAfterContentInit(){    
   console.log("after content init");   
   // this.aname = this.hello && this.hello.name  
}  
ngOnChanges(changes: SimpleChanges) {    
   console.log(changes)       
   this.xx = changes 
 }
}

RxJs : tap/do

Description: API / rxjs/operators
Transparently perform actions or side-effects, such as logging

import of } from 'rxjs';
import { tap, map from 'rxjs/operators';

const source = of(1, 2, 3, 4, 5);
//transparently log values from source with 'do'
const example = source.pipe(
    tap(val => console.log(`BEFORE MAP: ${val}`)),
    map(val => val + 10),
    tap(val => console.log(`AFTER MAP: ${val}`))
);
//'do' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

RxJS – switchMap

Description: API / rxjs/operators
The main difference between switchMap and other flattening operators is the cancelling effect. On each emission, the previous inner observable (the result of the function you supplied) is canceled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

Example RxJS:-switchMap

gg

RxJS

Introduction

RxJS is one of the latest libraries in web development. Offering a powerful, functional approach for dealing with events and with integration points into a growing number of frameworks, libraries, and utilities,

RxJS is a library for composing asynchronous and event-based programs by using observable sequences.

Observable Stream

  • – User Input
  • – Http Request
  • – Array
  • – Object

Observable Handle

  • – Data
  • – Error
  • – Completion

We can handle observable through of subscribe with three methods data,error and complete,

.subscribe(
(data) => console.log(data),
(error) => console.log(error),
() => console.log("Complete")
)

1- fromEvent

import {fromEvent} from 'rxjs'
fromEvent(this.addBtn.nativeElement,'click').subscribe((res)=> {console.log(res)})

2-Interval,timer

Example RxJS :- timer,interval,unsubscribe

@viewChild Angular

Property decorator that configures a view query
View queries are set before the ngAfterViewInit callback is called.

import { Component, OnInit,AfterViewInit,  viewChild } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit, AfterViewInit {

  constructor() { }
  @ViewChild('addBtn') addBtn:ElementRef;
  ngOnInit(): void {
  }
   ngAfterViewInit() {
    // child is set
    console.log(this.addBtn.nativeElement)
  }

}

<button #addBtn>add</button>

…………………………………………………………………………………………………………………………………….

@viewchildren

@viewchildren decorator returns the list of different native DOM elements through og QueryList
@ViewChild() in a component can communicate with another component or a directive.
But if we want to access multiple child references, then we have to use @ViewChildren.

import {AfterViewInit, ElementRef, viewChildren,QueryList} from '@angular/core'
export class AppComponent implements AfterViewInit {
// Accessing multiple native DOM elements using QueryList
  @ViewChildren(HelloComponent) myValue: QueryList<HelloComponent>;
  ngAfterViewInit() {
     console.log("Hello ", this.myValue.toArray(););
  }
}
<hello name="{{ name }}"></hello>

<hello name="{{ name }}"></hello>

<hello name="{{ name }}"></hello>

Angular PreloadingStrategy

app-routing.module.ts
 import { PreloadAllModules } from '@angular/router';
 @NgModule({ 
 imports: [
   RouterModule.forRoot(routes, { useHash: false, 
   onSameUrlNavigation: 'reload', 
   preloadingStrategy: PreloadAllModules })
  ],    
 exports: [RouterModule]  
})

.

Custom Preloading Strategy

app-routing.module.ts
import {CustomPreloadingStrategy} from './customPreloadingStrategy';
 import { PreloadAllModules } from '@angular/router';
 @NgModule({ 
 imports: [
   RouterModule.forRoot(routes, { useHash: false, 
   onSameUrlNavigation: 'reload', 
   preloadingStrategy: CustomPreloadingStrategy })
  ],    
 exports: [RouterModule]  
})
///////////////////////////////////////
{ path: 'dashboard', 
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
    data: { preload: true, delay:10000 
}

app.module.ts
import {CustomPreloadingStrategy} from './customPreloadingStrategy';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  ],
  providers: [CustomPreloadingStrategy],
  bootstrap: [AppComponent]
})

customPreloadingStrategy.ts -- service
import {Injectable} from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of, timer  } from 'rxjs';
import { flatMap } from 'rxjs/operators';

@Injectable()
export class CustomPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, loadMe: () => Observable<any>): Observable<any> {
    
        if (route.data && route.data['preload']) {
          var delay:number=route.data['delay']
          console.log('preload called on '+route.path+' delay is '+delay);
          return timer(delay).pipe(
            flatMap( _ => { 
              console.log("Loading now "+ route.path);
              return loadMe() ;
            }));
        } else {
          console.log('no preload for the path '+ route.path);
          return of(null);
        }
      }
}


Angular Guards

What are Route Guards?

Angular’s route guards are interfaces that can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false the return value from a class that implements the given guard interface.

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Router } from '@angular/router'
@Injectable()
   export class AuthService {
      constructor(
          private http: HttpClient,
          private _router: Router
         ) { }
       loggedIn() {
          return !!localStorage.getItem('token')
     }
}
CanActivate
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private _authService: AuthService,
    private _router: Router) { }

  canActivate(): boolean {
    if (this._authService.loggedIn()) {
      console.log('true')
      return true
    } else {
      console.log('false')            
      this._router.navigate(['/login'])
      return false
    }
  }
}

JavaScript Promise - Basics

Promises are used to handle asynchronous operations in JavaScript
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Benefits of Promises
1- Improves Code Readability
2- Better handling of asynchronous operations
3- Better flow of control definition in asynchronous logic
4- Better Error Handling

A Promise has four states:
1-fulfilled: Action related to the promise succeeded
2-rejected: Action related to the promise failed
3- pending: Promise is still pending i.e not fulfilled or rejected yet
A promise can be created using Promise constructor.

var promise = new Promise(function(resolve, reject){});

Difference between Promise and Observables
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

Observables
1-Emit multiple values over a period of time.
2-subscriptions that are cancellable using the unsubscribe() method

Promises
1-Emit a single value at a time, A promise can only handle one event
2-Are not cancellable.

Custom Promise

function cP(successCb,errorCb){
    setTimeout(()=>{
       let data ="ajay";
       if(data){
          successCb(data)
       } else{
          errorCb("no Data")
       }
    },2000)
}
cP((res)=>{console.log(res)},(er)=>{console.log(er)})

Angular routing- LazyLoad

In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different views that you have defined. To implement this kind of navigation within the single page of your app, you use the Angular Router.

Note: Routing helps you to define the navigations for your applications, so if you want to move one screen to another screen that no loading and refreshing the page

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '@app/home/home.component';
import { AuthGuard } from './guards/auth.gards';
const routes: Routes = [
{ path: 'home', component: HomeComponent, canActivate:[AuthGuard]},
{
  path: 'contact',
  loadChildren: './contact/contact.module#ContactModule',
  canActivate: [AuthGuard, CheckContactAddressGuard]
},
{
path: 'login',
loadChildren: './login/login.module#LoginModule'
},
{ path: 'unauthorized',component:UnauthorizedAccessComponent, canActivate:[AuthGuard]},
{ path:'**', redirectTo: '/home', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes,{useHash:true, onSameUrlNavigation:'reload'})],
exports: [RouterModule]
})
export class AppRoutingModule {
}

Angular setValue, patchValue

Angular setValue
Sets the value of the Form Group. It accepts an object that matches the structure of the group, with control names as keys.

Set the complete value for the form group
const form = new FormGroup({
  first: new FormControl(),
  last: new FormControl()
});
console.log(form.value); // {first: null, last: null}
form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value); // {first: 'Nancy', last: 'Drew'}
Continue reading “Angular setValue, patchValue”