Angular 4 5 6 Interview Question

Angular 4-5-6 Interview Question


/////////// Angualr 2/4/5/6/7 Interview Question ///////////

1.) What are the new features of Angular 4?

    Revamped *ngIf and *ng For
    Router ParamMap
    TypeScript Compatibility
    Animations Package
    Dynamic Components
    Angular Universal
    Smaller and Quick
    View Engine – AOT Compilation
    Flat ES Modules (Flat ESM / FESM)
    Source Maps for Templates

2.) Different between  Observable or Promise

    Promise:
        -A Promise handles a single event when an async operation completes or fails.
        -usually only use with async data return
        -not easy to cancel
    Observable:
        -are cancellable
        -are retriable by nature such as retry and retryWhen
        -stream data in multiple pipelines
        -having array-like operations like map, filter etc
        -can be created from other sources like events
        -they are functions, which could be subscribed later on
        -An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.
        -Observable provides operators like map, forEach, reduce, retry(), or replay().

3.) How to share data between Components

    --  @Input() teacher: Teacher;, @Input('principle') principleName: string;
    --  via @ViewChild

        --@ViewChild to inject a reference to a DOM element
            @ViewChild('title')title: ElementRef;

        --@ViewChild to inject a reference to a component
            import { EcchildComponent } from '../ecchild/ecchild.component';
            @ViewChild(EcchildComponent) counterComponent: EcchildComponent;

    --  via a Service
        import { Injectable } from '@angular/core';
        import { BehaviorSubject } from 'rxjs';
        @Injectable({
        providedIn: 'root'
        })
        export class approvalService {
            private approvalStageMessage = new BehaviorSubject('Basic Approval is required!');
            currentApprovalStageMessage = this.approvalStageMessage.asObservable();
            constructor() {}
            updateApprovalMessage(message: string) {
                this.approvalStageMessage.next(message)
            }
        }

        ///To get
            this.appService.currentApprovalStageMessage.subscribe(msg => this.message = msg)


4.) How to handle service error


5.) Use of Guard (or) CanActivate  For securing routes

        import { AuthService } from './../services/auth.service';
        import { Injectable } from '@angular/core';
        import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route } from '@angular/router';
        import { Observable } from 'rxjs';
        @Injectable()
        export class AuthGuard implements CanActivate {
            constructor(private _authService: AuthService, private _router: Router) {}
            canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean {
                if (this._authService.isAuthenticated()) {
                    return true;
                }
                // navigate to login page
                this._router.navigate(['/login']);
                // you can save redirect url so after authing we can move them back to the page they requested
                return false;
            }
        }

        ...
        import { AuthGuard } from '../guards/auth-guard.service';
        ...
        export const dashboardRoutes: Routes = [
        {
            ...
            component: LayoutComponent,
            canActivate: [AuthGuard],
            ...
        }
        ];

6.) What is component decorators in Angular 4?
    The main objectives of decorators is to add some metadata to the class that will tell Angular 4 how to process a class.


7.) What is compilation in Angular 4?

    time (JIT) compilation: This is a standard development approach which compiles our Typescript and html files in the browser at runtime,
    as the application loads. It is great but has disadvantages. Views take longer to render because of the in-browser compilation step.
    App size increases as it contains angular compiler and other library code that won’t actually need.

    Ahead-of-time (AOT) compilation: With AOT, the compiler runs at the build time and the browser downloads only the pre compiled version of the applicatio

8.) What is Directive in Angular 4?

    "Structural directives": change the DOM layout by adding and removing DOM elements. For example, *ngIf and *ngFor
    "Attribute directives":  change the appearance or behavior of an element. . For example, *ngStyle and *ngClass
    "Components are basically directives with a template.

    --Directives allow us to attach behavior to elements in the DOM, for example, doing something on mouse over or click

9.) What is Pure and Impure Pipes?

    --"Pure pipes" are "stateless" that flow input date without remembering anything or causing detectable side-effects.
        Pipes are pure by default, hence most pipes are pure. We can make a pipe impure by setting its pure flag to false.
        Angular executes a pure pipe only when it detects a pure change to the input value.
        A pure change is either a change to a primitive input value or a changed object reference.

    --"Impure pipes" are those which can manage the state of the data they transform. A pipe that creates an HTTP request,
        stores the response and displays the output, is a impure or stateful pipe. Stateful Pipes should be used cautiously.
        Angular provides AsyncPipe, which is stateful. In the following code, the pipe only calls the server when the request URL changes and it caches the server response.
        The code uses the Angular http client to retrieve

    @Pipe({
        name: 'fetch',
        pure: false
    })
    export class FetcJsonPipe implements PipeTransform{
        private cachedData:any = null;
        private cachedUrl: '';
        constructor(private http:Http){}
        transform(url:string):any{
            if(url !=this.cachedUrl){
                this.cachedUrl = url;
                this.http.get(url)
                .map(result=>result.json())
                .subscribe(result=>this.cachedData = result);
            }
            return this.cachedData;
        }
    }


10.) What is Redux?

    Answer: Redux is an open-source JavaScript library for managing use state.
     
       --Redux is an application state manager for JavaScript applications,
        and keeps with the core principles of the Flux-architecture by having a unidirectional data flow in our application.
        Redux applications have only one global, read-only application state. This state is calculated by “reducing” over a collection or stream of actions
        that update it in controlled ways.

11.) How to optimize Angular app?

    Consider lazy loading instead of fully bundled app if the app size is more.
    Make sure that any 3rd party library, which is not used, is removed from the application.
    Have all dependencies and dev-dependencies are clearly separated.
    Make sure the application doesn’t have un-necessary import statements.
    Make sure the application is bundled, uglified, and tree shaking is done.
    Consider AOT compilation.

Comments

Popular posts from this blog

Module Bundel

Power of async and Promise