Wednesday 21 February 2018

Get Url parameter using Angular

AngularQuery ParameterRouter

In this article we will be discussing about getting query parameter in Angular. In angular js 1.x, it was straight forward by using $location.search();. Now let us check how it is in Angular 2(+).

Sample Url


http://localhost:4200/experiment?userName="Prashobh"&profession="blogger"

Let us check the component code for accessing the query parameter.


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: 'experiment-com',
    templateUrl: '../experiment/experiment.html'
})

export class experimentComponent {
    constructor(private ActiveRoute: ActivatedRoute) { }
    ngOnInit() {
        this.ActiveRoute.queryParams.subscribe((params: Params) => {
            let _queryParem = params;
            console.log(_queryParem);

        })
    }
}

Here we have used ActivatedRoute and Params to get the data and getting those info in angular ngOnInit. It is pretty straight forward.

Example result

If you want to access particular value then you can try below code.


let _queryParem = params['userName'];
console.log(_queryParem);


Now let us check another scenario.

In this case we have added data in router in the above format. Let us check how we can access this in our component.


{ path: 'form', component: FormComponent ,data :{data :'Test Data'} },


import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
    selector: 'form',
    template: '<div>Form</div>'
})

export class FormComponent {
    sub: any;
    constructor(private route: ActivatedRoute) { }
    ngOnInit() {
        this.sub = this.route
            .data
            .subscribe(value => console.log(value));
    }
}

There are other ways also there to share and access data through routes, check this link for 3 simple ways to share data through angular route. and also Share data between Angular components - 7 methods

Angular 2+Angular 4/5Query ParameterRouter

Related Info

1. Http calls in Angular with simple examples.

2. 5 different ways for conditionally adding class - Angular.

3. Angular 2/4 routing with simple examples.

4. Reusable flashy message using Angular 4

Friday 16 February 2018

Reusable flashy message using Angular

AngularFlash MessageNon related componentBehaviorSubject

We are going to create a simple flash message that can be accessed by anywhere in the application. One of the use case will be, suppose we have many forms in our application and after submitting the forms we need to show a simple success message to the user. For those scenarios we can use this example. Success message will stay for some seconds and it will fade out. However you can control this effect as well. You can place this flashMessageComponent in your header so that it will be visible even after navigating to other pages as well. Let us check with an example.

Create a simple flashMessageComponent first.

Reusable flashy message using Angular


flashMessageComponent


import { Component, OnInit } from '@angular/core';
import { commonService } from '../services/commonService';

@Component({
    selector: 'flash-message',
    template: '<div class="flashMessage animateCss" [ngClass]="{\'showFlashmessage\': showMessage}" [hidden]="!showMessage">'
        + '<span>{{message}}</span>'
        + '</div>'
})

export class flashMessageComponent {
    showMessage: boolean;
    message: string;
    constructor(private _commonService: commonService) {
        this.showMessage = false;
    }

    ngOnInit() {
        this._commonService.currentMessage.subscribe(msg => this.updateMessage(msg))
    }

    updateMessage(msg: string) {
        if (msg && msg != '' && msg != null) {
            this.message = msg;
            this.showMessage = true;

            setTimeout(() => {
                this.showMessage = false;
                this.message = '';
            }, 3000);
        }

    }
}

We are done with flashMessageComponent. Place this <flash-message></flash-message> in your header (or where ever you feel it would be better to fit) so that user can see the message at top middle of the page. Here I have imported OnInit, basically here (ngOnInit) we will be getting the notification for latest message update. UpdateMessage is the method which will handle the message and pass to our html. In the html I have used ngClass to add or remove classes and hidden property of angular to show and hide. Next create a simple service file, in this case it is commonService.

Service (commonService.ts)

Let us check the code first.


import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class commonService {

    private message = new BehaviorSubject('');
    currentMessage = this.message.asObservable()

    constructor() { }

    updateFlashMessage(message: string) {
        this.message.next(message);
    }

}

Here we have used Angular BehaviorSubject and setting the data asObservable. From any component you can call this updateFlashMessage method by importing commonService file and also you can pass message along with that, this will be get updated in flashMessageComponent and the result will be a beautiful flashy message. Now let us check the code of the component where we will be calling this method.

Component


import { Component } from '@angular/core';
import { commonService } from '../../services/commonService';

@Component({
    selector: 'my-component',
    template: '<div>'
        + '<button class="btn" (click)="showMessage()">Show message</button>'
        + '</div>'
})

export class MyComponentOne {
    constructor(private _commonService: commonService) { }
    showMessage() {
        this._commonService.updateFlashMessage('I am a flash message');
    }
}

Import commonService and update the message. Basically you can invoke the flashy message from any component by adding the simple code mentioned above. Here I have used one of the component communication method to achieve above functionality. I suggest you to read about 7 method to communicate between angular components as well.

Below are the css which I have used to build this flash component, you can make it better by updating with your own css.

CSS


.flashMessage{
    position: absolute;
    top: 12px;
    left: 50%; 
    width: 350px;
    z-index: 1000000;
    pointer-events: none;
    background: #058405;
    text-align: center;
    padding: 5px 3px;
    border-radius: 5px;
    color: #fff;
    font-size:14px;
}
.animateCss{
    -webkit-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
    -moz-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
    -ms-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out ;
    -o-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
    transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
    opacity: 0;
}
.showFlashmessage{
    opacity: 2;
}

If you don’t want to create a global flash message, you can check this link: - Flash messages for related components.

We are done. In this article we have created a simple flash message which can be accessed from any component easily.

Angular 2+Angular 4/5Flash MessageNon related componentBehaviorSubject

Related Info

1. Http calls in Angular with simple examples.

2. 5 different ways for conditionally adding class - Angular.

3. Angular 2/4 routing with simple examples.

Friday 9 February 2018

Share data between non related components - Angular 2/5

AngularShare DataNon related componentBehaviorSubject

In this article we will be discussing about sharing a data between non related components. Here I have used angular BehaviorSubject. We have used $rootScope in Angular js 1 as a global variable. However there is no such concept in Angular 2 (+), still we can achieve the same using below concept. Let us check with one example. Here I am going to create a simple service file. Check the code below.

Service file


import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class commonService {
    private data = new BehaviorSubject('');
    currentData = this.data.asObservable()

    constructor() { }

    updateMessage(item: any) {
        this.data.next(item);
    }

}

Here we have created a new BehaviorSubject and assigned to currentData. We will be subscribing the currentData in component. Now let us check our components.

First components


import { Component } from '@angular/core';
import { commonService } from '../../services/commonService';

@Component({
    selector: 'sub-component-one',
    template: '<div>'
        + '<h3>Sub Component one</h3>'
        + '<input type="text" [(ngModel)]="queryTerm">'
        + '<button class="btn" (click)="shareData(queryTerm)">Trigger</button>'
        + '</div>'
})

export class SubComponentOne {
    queryTerm: any;
    currentValue: any;
    constructor(private _data: commonService) { }

    shareData() {
        this.currentValue = this.queryTerm;
        this._data.updateMessage(this.currentValue);
    }
}

Here I have added a text box and also a button to click. On click on Trigger button user entered value should display in the second component. Clicking on shareData method we are updating the method in the service. Now let us check second component.

Second component


import { Component, OnInit } from '@angular/core';
import { commonService } from '../../services/commonService';

@Component({
    selector: 'sub-component-two',
    template: '<div>'
        + '<h3>Sub Component two</h3>'
        + '<p>Current Value : {{currentValue}}</p>'
        + '</div>'
})

export class SubComponentTwo {
    currentValue: any;

    constructor(private _data: commonService) { }

    ngOnInit() {
        this._data.currentData.subscribe(currentData => this.currentValue = currentData)
    }
}

Here we are subscribing the data in ngOnInit. So whenever the user clicks on the trigger method in the first component, that will be get updated in the second component ngOnInit.

We are done.

There are many other ways also there to share data between components, for that read here - 7 method to share the data between components.

Angular 2+Angular 4/5Share DataNon related componentBehaviorSubject

Related Info

1. File/image upload and send data to backend - Angular

2. Show preview image while uploading - Angular