Friday, 19 January 2018

File upload validation - Angular

AngularFile UploadValidation

In this article we will be discussing about validating a file/image from client side before uploading. In my previous articles I have covered file upload and showing a preview image while uploading, now let us check the validation part.

Component


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

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',
})

export class AppComponent {
    constructor(private _service: commonService) { }

    upload(event: any) {
        let files = event.target.files;
        //check file is valid
        if (!this.validateFile(files[0].name)) {
            console.log('Selected file format is not supported');
            return false;
        }

        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));
        this._service.uploadFile(fData).subscribe(
            response => console.log(response),
            error => console.log(error)
        )
    }
}

Validation


validateFile(name: String) {
    var ext = name.substring(name.lastIndexOf('.') + 1);
    if (ext.toLowerCase() == 'png') {
        return true;
    }
    else {
        return false;
    }
}

Here we are taking the file/image extension and validating before uploading to backend. Similar way you can check other extensions as well.


if (ext.toLowerCase() == 'war')
if (ext.toLowerCase() == 'csv')
if (ext.toLowerCase() == 'jpeg')
...etc

We are done. In this article we have discussed about validating a file/image before uploading to backend.

Angular 2+Angular 4/5File UploadValidation

Related Info

1. File/Image upload validation- Angular

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular

5. Date filtering and formatting - Angular

Thursday, 18 January 2018

File upload and send data to backend - Angular

AngularFile UploadImage Upload

In this article we will be discussing about how to upload a file/image and send data to backend. In my previous article I have explained about showing a preview image while uploading a file/image. Let us start by creating a simple component.

Component


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

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',
})

export class AppComponent {

    constructor(private _service: commonService) { }

    upload(event: any) {
        let files = event.target.files;
        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file[]", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));

        this._service.uploadFile(fData).subscribe(
            response => this.handleResponse(response),
            error => this.handleError(error)
        )
    }
    handleResponse(response: any) {
        console.log(response);
    }
    handleError(error: string) {
        console.log(error);
    }
}

Upload method will capture the file parameter and you can append the data as well along with that. We are passing these details to a service file. Check below code for that.

Service file


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class commonService {
    _url: string;
    constructor(private http: Http) { }

    uploadFile(data: any): Observable<{}> {
        this._url = 'http://localhost:4200/XXXXXXXXXX/uploadFile';
        return this.http.post(this._url, data)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

You can use your own api depends on your backend code (Java, .Net etc.). We are passing byte array to backend. If you don't want to add additional parameters you can just pass only file data. Click on the button and test the file upload code by linking your backend code. If you want to show preview image while uploading refer this link. I have used angular http to make an API call, you can read more about angular http request calls here. Depends on your backend code you may need to pass some headers along with your http calls. Refer this link to know about passing headers along with http calls.

In this article we have discussed about uploading a file/image and sending data to backend.

Angular 2+Angular 4/5File UploadImage Upload

Related Info

1. File/Image upload validation- Angular

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular

5. Date filtering and formatting - Angular

Wednesday, 17 January 2018

Show preview image while uploading - Angular

AngularPreview imageUpload

In this article we are going to discuss about showing a preview image while uploading. This can be achieved by using very less code. Let's check below example

Preview image while uploading



import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="showPreviewImage($event)">'
        + '<img [src]="localUrl" *ngIf="localUrl" class="imgPlaceholder">'
        + '</div>',
})

export class AppComponent {
    localUrl: any[];
    constructor() { }
    showPreviewImage(event: any) {
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.localUrl = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
    }
}

While clicking on showPreviewImage method we are taking the selected image url and assigning to localUrl. We can a show a preview image and upload the selected file/image to backend as well. Check this link for that: - File upload and send data to backend. Here I have used *ngIf to hide the preview image section until it is available. You can do more things using Angular 4 ngIf. Check the difference between Angular 2 ngIf and Angular 4 ngIf here.

We are done. You can use css to improve the look and feel. In this article we have discussed about showing a preview image while uploading.

Angular 2+Angular 4/5Preview imageUpload

Related Info

1. File/Image upload validation- Angular 4

2. File/Image upload and send data to backend

3. Rating star component - Angular 4

4. Date filtering and formatting - Angular 4

Thursday, 21 December 2017

Share data between Angular components - 7 methods

Angular 2(+)Angular 4/5SiblingShare datacomponentsThrough routesServices

In this article we will be discussing about 7 different ways for sharing data between Angular components. I have written separate articles for the same in my previous posts. I am adding all those methods here.

  1. Share data between parent and child component.
  2. Share data between components using ViewChild.
  3. Share data between sibling components.
  4. Share data between components using service file.
  5. Share data through angular route.
  6. Create reusable component and pass data to component.
  7. Share data between non related components.

Let us check one by one.

1. Share data between parent and child component


This is one of the common scenario which you definitely should know to build an Angular application. Below are some of the common scenarios,

  1. Share data from parent component to child component
  2. Share data from child component to parent component
  3. Invoke child component method from parent component
  4. Invoke parent component method from child component

I have already written an article for the same, check below link for that.

Share data between parent and child component

2. Share data between components using ViewChild.


This is another way of sharing data between parent and child components. Here basically we are injecting other component and sharing the data. Check below link for the same.

Share data between components using ViewChild.

3. Share data between sibling components


This is another scenario which you may face while developing an Angular application. But you should try to avoid creating tow many siblings as it may not be a good idea. Check below links for sharing data between sibling’s components

Share data between sibling components

4. Share data between components using service file


This is another popular way of sharing data between components. By making a service common you can share data to any component. You don’t need to worry about parent, child or siblings, you can simply share data by making a service file common to both components. Check below links for the same.

Share data between components using service file

Communicate between components using service file

5. Share data through angular route.


This is another way of sharing data between components. It will help you while navigating from one component to another component. You can pass an array or object through routes.

  1. Pass data using route
  2. Pass data using Query Parameters
  3. Pass data using Application Providers

Check below link for to know more about different way of sharing data through routes.

3 simple ways to share data through angular route.

6. Create reusable component and pass data to component


You can simply create a component and which can reuse with in the application easily. You can share or receive data from this components. Check below link for that.

Create reusable component and pass data to component

7. Share data between non related components.


By using a simple service along with angular BehaviorSubject and ngOnInit, we can share data between non related components Very easily.

Share data between non related components - Angular 4

In this article we have discussed about various ways of sharing a data between angular components.

Angular 2(+)Angular 4/5SiblingShare datacomponentsThrough routesServices

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.

Wednesday, 20 December 2017

Share data between sibling components - Angular 2+

Angular 4SiblingShare datacomponents

In this article we will be discussing about sharing data between two different components. In my previous articles I have explained about different ways to share data between parent and child components. Now let us check in the case of sibling components.

Create a parent component first and then add other two components. Check below parent component.

Parent component


import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<home></home>'
        + '<dashboard></dashboard>'
        + '</div>',
})

export class AppComponent {
    constructor() { }
}

Here we have added two other components, which are not child or parent to each other. Now we need to share data from one component to another component. Before doing that let me share both component code below.

HomeComponent


import { Component } from '@angular/core';

@Component({
    selector: 'home',
    template: '<div><button (click)="shareData();">Share data</button>'
        + '</div>'
})

export class HomeComponent {
    constructor() { }
    shareData() {

    }
}

DashboardComponent


import { Component } from '@angular/core';

@Component({
    selector: 'dashboard',
    template: '<div>Dashboard</div>'
})

export class DashboardComponent {
    constructor() { }
}

On click of shareData() method, we need to share some data to DashboardComponent. Check below updated component.

Updated HomeComponent


import { Component, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'home',
    template: '<div><button (click)="shareData();">Share data</button>'
        + '</div>'
})

export class HomeComponent {

    @Output() shareDataEvent = new EventEmitter();

    _data: any[];

    constructor() {
        this._data = ['prashobh', 'angular', 'developer'];
    }
    shareData() {
        this.shareDataEvent.emit(this._data);
    }
}

We have added Output and EventEmittor to post the data.

Updated DashboardComponent


import { Component } from '@angular/core';

@Component({
    selector: 'dashboard',
    template: '<div>Dashboard</div>'
})

export class DashboardComponent {
    constructor() { }
    sendData(data: any[]) {
        console.log('I am from home component');
        console.log(data);
    }
}

Here we have added a method to receive data from other component. We are done for our components, now we need to update our parent component to pass the data.

Updated parent component


import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<home (shareDataEvent) = "dashboard.sendData($event)"></home>'
        + '<dashboard #dashboard></dashboard>'
        + '</div>',
})

export class AppComponent {
    constructor() { }
}

Here HomeComponent is emitting the data to parent and from parent it is sharing to DashboardComponent.

There are many other ways also there to share data between components. Check below articles for that.

1. Create reusable component and pass data to component.

2. Share data between components using service file.

3. Share data between parent and child component.

4. 3 simple ways to share data through angular route.

5. Share data between components using ViewChild.

6. How to communicate between a component and a service file.

We are done. In this article we have discussed about sharing data between two sibling components in Angular.

Angular 4SiblingShare datacomponents

Tuesday, 19 December 2017

Share data between components using ViewChild - Angular 2+

Angular 4ViewChildShare data

In this article we will discussing about sharing data between different components using ViewChild. There are many ways to share data between components, ViewChild is one among them. Let us check with some examples. Here I am going to create two components, HomeComponent and DashboardComponent.

HomeComponent


import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard.component'

@Component({
    selector: 'home',
    template: '<div><button (click)="shareData();">Share data</button>'
        + '<dashboard></dashboard>'
        + '</div>'
})

export class HomeComponent {

    constructor() { }
    shareData() {

    }
}

DashboardComponent


import { Component } from '@angular/core';

@Component({
    selector: 'dashboard',
    template: '<div>Dashboard</div>'
})

export class DashboardComponent {
    constructor() { }
    sendData(data: any[]) {

    }
}

We have created two simple components. Now write a logic to access sendData() method from HomeComponent. Check updated HomeComponent code.

Updated HomeComponent


import { Component, ViewChild } from '@angular/core';
import { DashboardComponent } from './dashboard.component'

@Component({
    selector: 'home',
    template: '<div><button (click)="shareData();">Share data</button>'
        + '<dashboard></dashboard>'
        + '</div>'
})

export class HomeComponent {
    constructor() { }

    @ViewChild(DashboardComponent) DashboardComponent: DashboardComponent;
    shareData() {
        this.DashboardComponent.sendData();
    }
}

Similar way you can share an array or object, check below code for that.


import { Component, ViewChild } from '@angular/core';
import { DashboardComponent } from './dashboard.component'


@Component({
    selector: 'home',
    template: '<div><button (click)="shareData();">Share data</button>'
        + '<dashboard></dashboard>'
        + '</div>'
})

export class HomeComponent {

    _data: any[];
    constructor() {
        this._data = ['prashobh', 'angular', 'developer'];
    }

    @ViewChild(DashboardComponent) DashboardComponent: DashboardComponent;
    shareData() {
        this.DashboardComponent.sendData(this._data);
    }
}

Updated DashboardComponent to receive data


import { Component } from '@angular/core';

@Component({
    selector: 'dashboard',
    template: '<div>Dashboard</div>'
})

export class DashboardComponent {
    constructor() { }
    sendData(data: any[]) {
        console.log('I am from home component');
        console.log(data);
    }
}

We are done. In this article we have discussed about sharing data from component to another component using ViewChild.

Angular 4ViewChildShare data

Related Info

1. Create reusable component and pass data to component.

2. Share data between components using service file.

3. How to communicate between a component and a service file.

4. Share data between parent and child component.

5. 3 simple ways to share data through angular route.

Friday, 15 December 2017

3 simple ways to share data through angular route.

Angular 2+Angular 4/5RoutingShare data

In this article I will be discussing about sharing data through routes in 3 simple ways. Compared to Angular js 1 it is so simple and there are many ways to achieve this. Let us check those one by one.

  1. Pass data using route
  2. Pass data using Query Parameters
  3. Pass data using Application Providers

1. Pass data using route


Here we are passing data directly through routes. Check below router code.

Router

Here we are passing data :{data :'Test Data'} to other component. Check below code for receiving the data.


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent ,data :{data :'Test Data'} },
]

Here I am passing the data through routes. For understanding routing more check this link: - Angular routing/nested routing with examples. We need to write some code to receive this data in other component. Check below code for that.


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));
    }
}

Similarly you can handle this logic inside your component as well. Instead of hardcoding the values in the routes, we can pass them in the component code as well. Create a clickable button in HomeComponent, on click of this button we will pass an id to FormComponent. Check below HomeComponent code.

HomeComponent


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

@Component({
  selector: 'home',
  template: '<div>Home : <button (click)="navigate();">Navigate to Form</button>'
    + '</div>'
})

export class HomeComponent {

  constructor(private router: Router) { }

  navigate() {
    this.router.navigate(['form', '0001']);
  }
}

On click of the method navigate, it will redirect to FormComponent. Inside the FormComponent we need to get the Id. Check below code for that.

FormComponent


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

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

export class FormComponent {
  sub: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      console.log(params);
    });
  }
}

Check the console you can see the id which we passed from HomeComponent. We need to make one more changes to make it work completely. Update router code like below.


{ path: 'form/:id', component: FormComponent }

Here you can notice that I have added id along with the path form/:id. There are some scenarios you might need to read values from query parameter. This url might be redirected from somewhere. Check this article for more info: - Get Url parameter using Angular.

2. Pass data using Query Parameters


This is the one of the way we used to pass data in angular js 1 and also for other routing method as well. Advantage of using angular 2/4 is the that it wont show any thing in your url but the same time you can pass data to other component. Another advantage is that you can pass complex data using this option. Let us check with one example.

Router


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent}
]

There is no additional thing here instead just routing code. Now check the component code there we will be adding a code for navigating to other page and also for sharing data.

Sharing Component


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

@Component({
    selector: 'home',
    template: '<div>Home : <br><button (click)="navigate();">Navigate to Form</button>'
        + '</div>'
})

export class HomeComponent {
    constructor(private router: Router) { }

    navigate() {
        let navigationExtras: NavigationExtras = {
            queryParams: {
                name: 'Prashobh',
                role: 'Angular developer'
            }
        }
        this.router.navigate(['form'], navigationExtras);
    }
}

Make sure you have imported NavigationExtras. We are passing these info to form page. Let us check FormComponent code.

Receiving component


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

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

export class FormComponent {
    constructor(private route: ActivatedRoute) {
        this.route.queryParams.subscribe(params => {
            console.log(params);
        });
    }
}

Here we have imported ActivatedRoute. Console the value and you can see the shared object.

3. Pass data using application providers


This is another method but it is not actually related to routes. You can use this approach to share your data across your application. We need to create a provider file first.

Provider


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

@Injectable()
export class DataStorage {
    public data: any;
    public constructor() { }
}

Don't forget to import your newly created provider in module. Now check our components.

Sharing component


import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { DataStorage } from "../dataProvider";


@Component({
    selector: 'home',
    template: '<div>Home'
        + '<br><button (click)="navigateToForm();">Navigate to Form</button>'
        + '</div>'
})

export class HomeComponent {

    constructor(private router: Router, private _data: DataStorage) { }

    navigateToForm() {
        this._data.data = {
            name: 'Prashobh',
            role: 'Angular developer'
        }
        this.router.navigate(['form']);
    }
}

Here we have imported our DataStorage provider and setting data to it before navigating. Now check our receiver part.

Receiving component


import { Component } from '@angular/core';
import { DataStorage } from "../dataProvider";

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

export class FormComponent {
    public constructor(private _data: DataStorage) {
        console.log(JSON.stringify(this._data.data));
    }
}

Import DataStorage provider here as well and just console the value.

We are done. Apart from this we can communicate with components using parent child communication logic or by making a service file common to both of the component.

In this article we have discussed about sharing data through routes with different examples.

Angular 2+Angular 4/5RoutingShare data

Related Info

1. 3 simple ways to share data through angular route.

2. Get Url parameter using Angular.

3. Share data between Angular components - 7 methods.

4. Conditionally add class using Angular - 5 methods

Wednesday, 13 December 2017

Angular 2/4 routing with simple examples and share data using route.

Angular 4RoutingNavigateShare data

Here I am going to explain about implementing routing in Angular with simple examples. Angular team made routing so simple, let us check with some examples.

  1. Angular simple routing
  2. Navigate from component
  3. Pass data to component using route
  4. Nested routing

1. Angular routing


I going to create HomeComponent and FormComponent, clicking on Home/Form link it should navigate to the desired page/component. Check below image for understanding our simple folder structure.

Let us start with our Module code.

Module


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';
import { appRoutes } from './routing';

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        FormComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(appRoutes)
    ],
    providers: [],
    bootstrap: [AppComponent]

})
export class AppModule { }

Here we have imported all the dependencies and appRoutes is our router file. Don't add appRoutes under declarations as it is not a component or pipe. If you add it under declarations angular will throw error.

AppComponent


import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<a routerLink="home" routerLinkActive="active">Home</a>'
        + '<a routerLink="form" routerLinkActive="active">Form</a>'
        + '<router-outlet></router-outlet>'
        + '</div>',
})

export class AppComponent {
    constructor() { }
}

Here <router-outlet></router-outlet> is angular representation for adding routing capabilities. Here I have used routerLinkActive, which will add active class on click. You can simply give some css for active class for highlighting the link on click. If you want to know more about adding class conditionally check these links: 5 different ways for conditionally adding class and Conditionally add class to an element on click.

Check below Router file code

Router


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent },
]

Here also we need to import the particular component and also import RouterModule and Routes. Before going for more details let me share HomeComponent and FormComponent code as well.

HomeComponent


import { Component } from '@angular/core';

@Component({
    selector: 'home',
    template: '<div>Home</div>'
})

export class HomeComponent {
    constructor() { };
}

FormComponent


import { Component } from '@angular/core';

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

export class FormComponent {
    constructor() { }
}

We are done. Click on the Home link it will navigate to http://localhost:4200/home and to http://localhost:4200/form on click of form link. If you want to redirect on some path initially you can add below code.


{ path: '', redirectTo: 'home', pathMatch: 'full' }

If user types some wrong url, you can force him navigate to some page. Check below code for that.


{ path: '**', redirectTo: 'home', pathMatch: 'full' }

If user types http://localhost:4200/hshshsshshsh ,then it will navigate to home page. Basically Angular team made routing so simple.

Check below complete router code


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent },
    { path: '**', redirectTo: 'home', pathMatch: 'full' }
]

2. Navigate from component


Now let us check how we can navigate from component to another on some action. Let us check that with a simple example. I will be adding a button in the home page, on click of that it should navigate to form page.


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

@Component({
    selector: 'home',
    template: '<div>Home : <button (click)="navigate();">Navigate to Form</button></div>'
})

export class HomeComponent {
    constructor(private router: Router) { }
    navigate() {
        this.router.navigate(['form']);
    }
}

We have used angular navigate method to achieve this.

3. Pass data to component using route.


Let us check how we can pass data to a component using route. I am adding some test data to our routing file. Check below code.


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

We are passing data :{data :'Test Data'} to FormComponent on click on form link. We need to add some code in our FormComponent to receive this 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));
    }
}

We are done. Don't forget to import ActivatedRoute. But remember this is not a preferred way to do this. Use parent child communication feature or make a service common to both component and share the data. There are other different ways to share data through routes check this link:- 3 simple ways to share data through routes.

4. Nested routing


Let us check how we can do nested routing. I will be creating two folder inside Form folder, aboutForm and contactForm. We will add two links to access this ichild components.

Updated Router


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';
import { AboutFormComponent } from './Form/aboutForm/aboutform.component';
import { ContactFormComponent } from './Form/ContactForm/contactform.component';

export const appRoutes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    {
        path: 'form', component: FormComponent,
        children: [
            { path: '', component: AboutFormComponent },
            { path: 'about-form', component: AboutFormComponent },
            { path: 'contact-form', component: ContactFormComponent }
        ]
    },
    { path: '**', redirectTo: 'home', pathMatch: 'full' }
]

It is very simple, just add under children rest angular will take care. Don’t forget to import your new components into module. Now let us check FormComponent code.


import { Component } from '@angular/core';

@Component({
    selector: 'form',
    template: '<div>'
        + '<h4>Form</h4>'
        + '<a routerLink="about-form" routerLinkActive="active">About Form</a>'
        + '<a routerLink="contact-form" routerLinkActive="active">Contact Form</a>'
        + '<router-outlet></router-outlet>'
        + '</div>'
})

export class FormComponent {
    constructor() { }
}

Here you can notice that we added <router-outlet></router-outlet> and this is required. Click on Form it will navigate to Form page then you can select About Form or Contact Form link to access child components. Angular team made nested routing so simple. I will share AboutFormComponent and ContactFormComponent code as well below.


import { Component } from '@angular/core';

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

export class AboutFormComponent {
    constructor() { }
}


import { Component } from '@angular/core';

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

export class ContactFormComponent {
    constructor() { }
}

In this article we have discussed about implementing a simple routing as well as nested routing using Angular and also about navigating from component itself.

Angular 4RoutingNavigateShare data

Related Info

1. Http calls in Angular with simple examples.

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

Monday, 11 December 2017

Conditionally add class using Angular - 5 methods

Angular[ngClass][style]conditionally add class

Here I am going to discuss about adding a class conditionally using Angular concept. I have explained about adding a class to an element on click in the previous article. Now let us check 5 different ways to add class dynamically. Similar way you can add styles directly as well.

  1. Directly binding with [style.background-color]
  2. Adding a class [class.active]
  3. Using NgClass [ngClass]
  4. Set multiple classes
  5. Set multiple styles

1. Directly binding with [style.background-color]


Let us check with an example about how to bind styles directly using Angular.


<div [style.border]="isActive ? '1px solid #ccc': 'none'">
  Conditionally add styles...
</div>
<button (click)="isActive = !isActive;">Toggle style</button>

Let us check the same with another example.


<div [style.background-color]="updateStyle()">
  Conditionally add styles...
</div>
<button (click)="toggleStyle = !toggleStyle;">Toggle style</button>


toggleStyle: boolean = false;

updateStyle() {
  if (this.toggleStyle) {
    return "red";
  } else {
    return "";
  }
}

I have used Angular [style] property to add styles here.

2. Adding a class [class.active]


Let us check how to add a class using Angular [class].


<div [class.active]="isActive">
  Conditionally add class...
</div>
<button (click)="isActive = !isActive;">Toggle style</button>

You can set single class using above method.

3. Using NgClass [ngClass]


Let us check by using [ngClass].


<div [ngClass]="{'active': isActive }">
  Conditionally add class...
</div>
<button (click)="isActive = !isActive;">Toggle style</button>

You can use turnery operator for adding either of any classes, check below example for that.


<div [ngClass]="isActive ? 'active':'anotherClass' ">
  Conditionally add class...
</div>
<button (click)="isActive = !isActive;">Toggle style</button>

4. Set multiple classes


Let us check how we can conditionally add set of classes.


<div [ngClass]="setClasses()">Conditionally set classes </div>


toggleStyle: boolean = false;
anotherClass: boolean = false;

setClasses() {
  let classes = {
    activeClass: this.toggleStyle,
    anotherclass: this.anotherClass
  };
  return classes;
}

Similar way you can conditionally add multiple classes, this will be very useful while building your application.

5. Set multiple styles


Similar like classes we can set multiple styles as well. See below example.


<div [ngStyle]="setStyles()">Conditionally set styles</div>


toggleStyle: boolean = false;
anotherClass: boolean = false;

setStyles() {
  let styles = {
    'color': this.toggleStyle ? 'red' : 'blue',
    'font-weight': this.anotherClass ? 'bold' : 'normal'
  };
  return styles;
}

Depending on the condition you can set multiple styles.

We are done. Using above concept we can add or remove classes dynamically on click. Check this link for that example: - Conditionally add or remove class on element click.

In this article we have discussed about conditionally adding a class to an element with different examples.

Angular 2+Angular 4/5[ngClass][style]conditionally add class

Related Info

1. Http calls in Angular with simple examples.

2. Angular client side pagination.

3. Angular show more/less pagination