Archive

Archive for the ‘Angular2’ Category

Angular2 – Sharing data between two components

angular-2-tutorialAngular2 is a fully component driven framework. Each component has its own html template where you can bind the data to this template through the respective component.

What if you need to share some data within two component? May be you need to modify the same data/variable inside multiple components.

For example,inside both navBarComponent and AppComponent, we need to change the header text of the nav bar.

First you need to write a service for storing data as angular Observebles.

import { Injectable } from '@angular/core';
import { Observable,Subject } from 'rxjs/Rx';

// lessonService to be shared within the application
@Injectable()
export class TestService {

  constructor() { }

    // Observable string sources
  private selectedTestSource = new Subject<string>();

  // Observable string streams
  selectedTestSource$ = this.selectedTestSource.asObservable();

  // Service message commands
  setSelectedTestItem(param: string) {
    this.selectedTestSource.next(param);
  }

}

Now inject this service into Component 1.


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

  constructor(private testService:TestService) { }

  ngOnInit() {
  }

changeTest(testId:string){
  this.testService.setSelectedTestItem(testId);
}
}

Now access this value inside the other component using a  subscriber.

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

export class AppComponent implements OnDestroy {

constructor(private testService:TestService) {
this.subscription = testService.selectedTestSource$.subscribe(
testId=&gt;{
// add your code here
});
}

ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}

}

 

Categories: Angular2

Angularjs Routing – Angular1 vs Angular2

Before we start and to make sure we are in line on the terminology, I will use the name AngularJS to define AngularJS 1.x and Angular2 to define AngularJS 2.x.

AngularJS

To enable Hash (#) urls,  set the following configuration. This will shift within two nodes.(HTML5 enable mode or not)

$locationProvider.html5Mode(true);

Angular2

In Angular2 , same modes are called as PathLocationStrategy and HashLocationStrategy

PathLocationStrategy is the default strategy which is used by Angular2. This is equivalent to HTML5 mode in AngularJS.

import {ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
 
bootstrap(yourApp, [
  ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
  provide(APP_BASE_HREF, {useValue: '/my/prefix/here'})
]);

HashLocationStrategy will add hash fragment to URL.

import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';  // works only for rc6 ,
// for others  import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
 //  import {LocationStrategy,HashLocationStrategy }from '@angular/common';
bootstrap(yourApp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

Define Routes

AngularJS

$stateProvider.state('home', {
    url: '/',
    templateUrl: 'home.html',
    controller: 'HomeCtrl'
}).state('about', {
    url: '/about',
    templateUrl: 'about.html',
    controller: 'AboutCtrl'
})

Angular2

import {RouteConfig, Route} from 'angular2/router';
import {MyComponentHome, MyComponentAbout} from './myComponents';
@Component({
    selector: "app"
})
@RouteConfig([
    new Route({ path: '/', component: MyComponentHome, name: 'Home' }),
    new Route({ path: '/about', component: MyComponentAbout, name: 'About' })
])
export class App {...}

Template Update

AngularJS

<body>
    <ui-view>
        <i>Some content will load here!</i>
    </ui-view>
</body>

Angular2

import {RouterOutlet} from 'angular2/router';
@Component({
    selector: "app"
})
@View({
    directives: [RouterOutlet]
    template: `
      <router-outlet></router-outlet>
    `
})

Navigate through views

AngularJS

<a ui-sref="home">Home page</a>
<a ui-sref="about">About page</a>

Angular2

import {RouterLink} from 'angular2/router';
@Component({
  selector: "menu",
  directives: [RouterLink],
  template: `
     <a [routerLink]="['./Home']">Home page</a>
     <a [routerLink]="['./About']">About page</a>
  `
})
export class Menu {...}