0% found this document useful (0 votes)
3 views20 pages

Angular

The Component Router Guide for AngularJS 1.5 introduces a new way to build component-based applications with a focus on routing and navigation. It explains how to set up routes, manage components, and utilize lifecycle hooks for better control over component behavior during navigation. The guide also provides practical examples for implementing features like a Heroes list and detail views, along with instructions for configuring the application and using services.

Uploaded by

Syed Adnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Angular

The Component Router Guide for AngularJS 1.5 introduces a new way to build component-based applications with a focus on routing and navigation. It explains how to set up routes, manage components, and utilize lifecycle hooks for better control over component behavior during navigation. The guide also provides practical examples for implementing features like a Heroes list and detail views, along with instructions for configuring the application and using services.

Uploaded by

Syed Adnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Component Router Guide

This guide describes the new Component Router for AngularJS 1.5.

If you are looking for information about the old router for AngularJS 1.4 and earlier have a look
at the `ngRoute` module.

If you are looking for information about the Component Router for Angular 2 then check out the
Angular 2 Router Guide.

Conceptual Overview

Component­based Applications
It recommended to develop AngularJS applications as a hierarchy of Components. Each
Component is an isolated part of the application, which is responsible for its own user interface
and has a well defined programmatic interface to the Component that contains it. Take a look at
the Component guide for more information.

URLs and Navigation


In most applications, users navigate from one view to the next as they perform application tasks.
The browser provides a familiar model of application navigation. We enter a URL in the address
bar or click on a link and the browser navigates to a new page. We click the browser's back and
forward buttons and the browser navigates backward and forward through the history of pages
we've seen.
We understand that each view corresponds to a particular URL. In a Component­based
application, each of these views is implemented by one or more Components.

Component Routes
How do we choose which Components to display given a particular URL?

When using the Component Router, each Component in the application can have a Router
associated with it. This Router contains a mapping of URL segments to child Components.

```js

$routeConfig: [

{ path: '/a/b/c', component: 'someComponent' }, ...

```

This means that for a given URL the Router will render an associated child Component.

Outlets
How do we know where to render a child Component?

Each Component that has Routes, needs to have a template that contains one or more Outlets,
which is where its child Components are rendered. We specify the outlet in the template using
the `<ng­outlet>` element directive.

```html

<ng­outlet></ng­outlet>

```

TODO: in the future ng­outlet will be able to render different child components by specifying a
name attribute.

RootRouter
How does the Component Router know which Component to render first?
Component Router applications must contain a top level Router, which is the starting point for
all navigation. In Angular 2, there is always a top level Component, which holds the Root
Router. In Angular 1, we don't have such a top level Component, so we have a stand­alone
RootRouter, which is configured via the `$router` service.

```js

$router.config([ { path: '/a/b/c', component: 'someComponent' }, ... ]);

```

Route Matching
When we navigate to any given URL, the Root Router matches the its Routes against the URL.
If a Route matches, the Component associated with the Route is instantiated and rendered in
the Outlet. If the new Component contains routes of its own, then , a new ChildRouter is created
for this component.

The ChildRouter for the new Component then attempts to match its Routes against any part of
the URL that has not already been matched by the previous Router.

This process continues until we run out of new Routes or consume the entire URL.

Here you can see that the URL /heros/2 has been matched against the App, Heroes and
HeroDetail Components. The Routers for each of the Components consumed a part of the URL:
"/", "/heroes" and "/2" respectively. The result is that we end up with a hierarchy of these
Components rendered via `ng­outlet` directives in our view.

Getting Started
Let's build a small application that uses the Component Router. The finished application will
have views to display list and detail views of Heroes and Crises.

Install the libraries


It is simplest to use npm to install the Component Router. For this guide we will also install
AngularJS itself via npm:

```bash

npm init

npm [email protected] angular ­­save

npm install @angular/router@^0.2 ­­save

```
TODO: We must specify these version ranges to make sure we get the correct router files for
this walkthrough.

Load the scripts


Just like any Angular application, we load the JavaScript files into our index.html:

```html

<script src="/node_modules/angular/angular.js"></script>

<script src="/node_modules/@angular/router/angular1/angular_1_router.js"></script>

<script src="/app/app.js"></script>

```

Create the application module


In our app.js file, we create our main application module `app` which depends upon
`ngComponentRouter`.

```js

angular.module('app', ['ngComponentRouter'])

```

We must choose what LocationMode the Router should use. We are going to use HTML5 mode
locations, so that we will not have hash­based paths. We must rely on the browser to provide
`pushState` support, which is true of most modern browsers.

This means that we can have clean URLs for our application routes but it does require that our
web server, which hosts the application, understands that it must respond with the index.html
file for requests to URLs that represent all our application routes. We are going to use the
`lite­server` web server to do this for us.

```js

.config(function($locationProvider) {

$locationProvider.html5Mode(true);
})

```

Configure the Root Router with a single Route, which maps the `/` URL to the `App`
Component.

```js

.run(function($router) {

$router.config([

{ path: '/', name: 'App', component: 'app', useAsDefault: true }

]);

})

```

Create a very simple App Component to show that the application is working.

We are using the new Angular 1.5 `.component()` helper method to create all the Components
in our application. It is perfectly suited to this task.

```js

.component('app', {

template: 'It worked!'

});

```

Add a `<base>` element to the head of our index.html.

Remember that we have chosen to use HTML5 mode for the `$location` service. This means
that our HTML must have a base URL.

```html
<head>

<base href="/">

...

```

Bootstrap AngularJS
Bootstrap the Angular application and add the top level Outlet (ng­outlet) where the RootRouter
will render the App Component.

```html

<body ng­app="app">

<h1 class="title">Component Router</h1>

<ng­outlet></ng­outlet>

</body>

```

You can see this initial application below:

<< Insert running example>>

Implementing the AppComponent


In the previous section we created a single top level Route definition, which mapped through to
the App Component. Let's now create some more Components and wire up Routes for those.

Let's implement a Heroes Feature in our application, which will display one of two views:
● A list of Heroes that are available:

● A detailed view of a single Hero:


We are going to have a Heroes Component for the Heroes feature of our application, and then
HeroList and HeroDetail Components that will actually display the two different views.

App Component
Configure the App Component with a template and route configuration:

```js

.component('app', {

template:

'<nav>\n' +

' <a >Crisis Center</a>\n' +

' <a ng­link="[\'Heroes\']">Heroes</a>\n' +

'</nav>\n' +

'<ng­outlet></ng­outlet>\n',

$routeConfig: [

{path: '/heroes/...', name: 'Heroes', component: 'heroes'},

});

```

The App Component has an `<ng­outlet>` directive in its template. This is where the child
Components of this view will be rendered.

ngLink
We have used the `ng­link` directive to create a link to navigate to the Heroes Component. By
using this directive we don't need to know what the actual URL will be. We can leave the Router
to generate that for us.
We have included a link to the Crisis Center but have not included the `ng­link` directive as we
have not yet implemented the CrisisCenter component.

Non­terminal Routes
We need to tell the Router that the `Heroes` Route is non­terminal, that it should continue to
match Routes in its child Components. We do this by adding a continuation ellipsis (`...`) to the
path of the Heroes Route, `/heroes/...`. Without the continuation ellipsis, the HeroList Route will
never be matched because the Router will stop at the Heroes Component and not try to match
the rest of the URL.

Implementing the Heroes Feature


Now we can implement our Heroes Feature which consists of three Components: Heroes,
HeroList and HeroDetail. The Heroes Component simply provides a template with `ng­outlet`
and a `$routeConfig` property to define a set of child Routes which delegate through to the
HeroList and HeroDetail components.

HeroesComponent
Create a new Angular module in heroes.js for the components of this feature and register the
`heroes` component.

```js

angular.module('heroes', [])

.component('heroes', {

template: '<h2>Heroes</h2><ng­outlet></ng­outlet>',

$routeConfig: [

{path: '/', name: 'HeroList', component: 'heroList', useAsDefault: true},

{path: '/:id', name: 'HeroDetail', component: 'heroDetail'}

})
```

Remember to load this file in the index.html and also to add the module as a dependency of the
`app` module.

The `useAsDefault` property on the `HeroList` Route, indicates that if no other Route matches
the URL, then this Route should be used by default.

The `HeroDetail` Route has a named parameter (`id`), indicated by prefixing the URL segment
with a colon, as part of its `path` property. The Router will match anything in this segment and
make that value available to the HeroDetail component.

Both the Routes in the `HeroesComponent` are terminal, i.e. their routes do not end with `...`.
This is because the `HeroList` and `HeroDetail` will not contain any child routes.

What is the difference between the “name” and “component” properties on a Route?

The `component` property in a Route is the name of the Component directive that will be
injected into the DOM via the Outlet. For example the `heroDetail` component will be injected
into the content of the `<ng­outlet></ng­outlet>` as `<hero­detail></hero­detail>.

The `name` property is only used to reference the Route when generating URLs or navigating to
Routes, for example: ``

HeroList Component
The HeroList Component is the first component in the application that actually contains
significant functionality. It loads up a list of heroes from a `heroService` and displays them using
`ng­repeat`. Add it to the heroes.js file:

```js

.component('heroList', {

template:

'<div ng­repeat="hero in $ctrl.heroes">\n' +

'<a ng­link="[\'HeroDetail\', {id: hero.id}]">{{hero.name}}</a>\n' +

'</div>',
controller: HeroListComponent

})

```

The `ng­link` directive creates links to a more detailed view of each hero, via the expression
`['HeroDetail', {id: hero.id}]`. This expression is an array describing what Routes to use to
generate the link. The first item is the name of the HeroDetail Route and the second is a
parameter object that will be available to the HeroDetail Component.

The HeroDetail section below explains how to get hold of the `id` parameter of the HeroDetail
Route.

The template iterates through each of an array of heroes on the `$ctrl.heroes` property.

Remember that the `module.component()` helper automatically provides the component's


controller on the scope of the template as the `$ctrl` property.

HeroService
The HeroService simulates requesting a list of heroes from a server.

```js

function HeroService($q) {

var heroesPromise = $q.when([

{ id: 11, name: 'Mr. Nice' },

...

]);

this.getHeroes = function() {

return heroesPromise;


this.getHero = function(id) {

return heroesPromise.then(function(heroes) {

for(var i=0; i<heroes.length; i++) {

if ( heroes[i].id == id) return heroes[i];

});

```

Note that both the `getHeroes()` and `getHero(id)` methods return a promise for the data. This is
because in real­life we would have to wait for the server to respond with the data.

Router Lifecycle Hooks


How do I know when my Component is active?

To aid with initialization and tidy up of Components that are created by a Router, we can
implement one or more "lifecycle hook" methods on the Component's Controller, which will be
called at well defined points in the life­cycle of the Component. The hooks are as follows:

● $routerCanReuse : called to to determine whether a component should be reused


across routes, or whether to destroy and instantiate a new component.
● $routerOnActivate / $routeOnReuse : called by the router at the end of a successful
route navigation. Only one of $routerOnActivate and $routerOnReuse will be called
depending upon the result of a call to $routerCanReuse.
● $routerCanDeactivate : called by the router to determine if a component can be removed
as part of a navigation.
● $routerOnDeactivate : called by the router before destroying a component as part of a
route change.

In addition we can provide a function ($routerCanActivate) on the component definition object


that will determine whether this component is allowed to be activated. If any of the
`$routerCan...` methods return false or a promise that resolves to false, the navigation will be
cancelled.

For the HeroList component we want to load up the list of heroes when the component is
activated. So we implement the `$routerOnActivate()` method.

```js

function HeroListComponent(heroService) {

var $ctrl = this;

this.$routerOnActivate() {

heroService.getHeroes().then(function(heroes) {

$ctrl.heroes = heroes;

});

```

Running the application should update the browser's location to /heroes and display the list of
heroes returned from the `heroService`.

HeroDetailComponent
How do I access parameters for the current route?

The HeroDetailComponent displays details of an individual hero. The id of the hero to display is
passed as part of the URL. The Router parsers the id out of the URL when it matches the Route
and provides it to the Component via the `$routerOnActivate` hook.

```js

function HeroDetailComponent(heroService) {

var $ctrl = this;


this.$routerOnActivate = function(next) {

// Get the hero identified by the route parameter

var id = next.params.id;

heroService.getHero(id).then(function(hero) {

$ctrl.hero = hero;

});

```

Accessing Route Parameters


The `$routerOnActivate` hook receives a `next` parameter, which holds an Instruction object for
the Route that is being activated. This object has a property called `params` which will hold the
`id` parameter extracted from the URL by the Router. This is used to get a specific Hero from
the `heroService`, which is then attached to the component so that it can be accessed in the
template.

Access to the Current Router


The HeroDetail component displays a form that allows the Hero to be modified.

```js

.component('heroDetail', {

template:

'<div ng­if="$ctrl.hero">\n' +

' <h3>"{{$ctrl.hero.name}}"</h3>\n' +

' <div>\n' +

' <label>Id: </label>{{$ctrl.hero.id}}</div>\n' +


' <div>\n' +

' <label>Name: </label>\n' +

' <input ng­model="$ctrl.hero.name" placeholder="name"/>\n' +

' </div>\n' +

' <button ng­click="$ctrl.gotoHeroes()">Back</button>\n' +

'</div>\n',

bindings: { $router: '<' },

controller: HeroDetailComponent

});

```

The template contains a button to navigate back to the HeroList. We could have styled an
anchor to look like a button and used `ng­link="['HeroList']" but here we navigate
programmatically via the Router itself.

Component Binding
How do I get hold of the current router for my component?

Each component has its own Router, and so unlike in Angular 2, we cannot use the injector to
get hold of a component's Router. We can only inject the `$rootRouter`. Instead we use the fact
that the `ng­outlet` directive binds the current router to a `$router` attribute on our component.

```html

<ng­outlet><hero­detail $router="$$router"></hero­detail></ng­outlet>

```

We use the bindings property on our component definition to bind the current router to our
component:

```js
bindings: { $router: '<' }

```

This sets up a one­way binding of the current Router to the `$router` property of our
Component. The binding is available once the component has been activated, and the
`$routerOnActivate` hook is called.

As you might know from reading the Component guide, the binding is actually available by the
time the `$onInit` hook is called, which is before the call to `$routerOnActivate`.

$router.navigate()
Once we have a reference to the current router we can use it to navigate to a new Route.

```js

this.gotoHeroes = function() {

this.$router.navigate(['HeroList']);

```

Here we are asking the Router to navigate to a route defined by `['HeroList']`. This is the same
kind of array used by the `ng­link` directive. The only item in the array is the name of the
HeroList route.

Other options for generating this navigation are:

● manually create the URL and call `this.$router.navigateByUrl(url)` ­ this is discouraged


because it couples the code of your component to the router URLs.
● generate an Instruction for a route and navigate directly with this instruction.
```js
var instruction = this.$router.generate(['HeroList']);
this.$router.navigateByInstruction(instruction);
```
­ this form give you the possibility of caching the instruction, but is more verbose.

Why not use `$rootRouter` to do the navigation?


Instead of binding to the current router, we can inject the $rootRouter into our Component and
use that: `$rootRouter.navigate(...)`.

The trouble with doing this is that the navigation is always relative to the current route. So in
order to navigate to the HeroListComponent with the $rootRouter, we would have to provide a
complete list of Routes: `['App','Heroes','HeroList']`.

Optional Parameters
We can also pass additional optional parameters to route, which get encoded into the URL and
are again available on the Instruction. If we pass the current id from the HeroDetailComponent
back to the HeroListComponent it could highlight the previously selected hero.

```js

this.gotoHeroes = function() {

var heroId = this.hero && this.hero.id;

this.$router.navigate(['HeroList', {id: heroId}]);

```

Then in the HeroList component we can extract this `id` in the $routerOnActivate()` hook.

```js

function HeroListComponent(heroService) {

var _selectedId = null;

var $ctrl = this;

this.$routerOnActivate = function(next) {

heroService.getHeroes().then(function(heroes) {

$ctrl.heroes = heroes;
_selectedId = next.params.id;

});

this.isSelected = function(hero) {

return (hero.id == _selectedId);

```

and then use the `id` to style the current hero in the template.

```html

<div ng­repeat="hero in $ctrl.heroes"

ng­class="{ selected: $ctrl.isSelected(hero) }">

<a ng­link="['HeroDetail', {id: hero.id}]">{{hero.name}}</a>

</div>

```
(implicit, is a commonly understood cultural or emotional
association that some word or phrase carries, in addition to the word's or phrase's explicit or
literal meaning, which is its denotation. The denotation is a representation of a cartoon heart.
The connotation is a symbol of love and affection. The denotation of dog is (something like)
four­legged canine carnivore. So saying, "You are a dog" would imply that you were ugly or
aggressive rather than stating that you were canine. )
Fantasy and fiction are sometimes used with a negative connotation, especially by the people
who do not consider them as being part of reality. They are, however, as real as your plans and
dreams about the future and they can offer lessons that you cannot find in schools or logic
textbooks. The relationship between fantasy and fiction is intricate and intertwined; yet, clearly
fantasy belongs to the fiction literary genre. (Fiction is a fake story that has the ability to be true
in the real world.)
Fantasy, as an invented story, is a form of fiction. The main difference between fantasy and
other types of fiction, such as science fiction, is that fantasy usually involves a mystical base, i.e.
magical, mythical or supernatural, imagined worlds, while science fiction makes use of an
analytical, scientific discourse and focuses on technology. Science fiction depicts the world as it
may become one day, while fantasy describes it as the possible ideal world.

a person to whom money is paid or is to be paid, especially the person to whom a check is
made payable.
I was talking with my architect about some concerns with a particular approach that may result
in very low level of cohesion in a set of classes. However, I couldn't think of the word that
represents a low level of cohesion.
I said something along the lines of "Obviously, we want cohesive classes not... uh ... not
cohesive classes"
Cohesion is an ordinal type of measurement and is usually expressed as “high cohesion” or “low
cohesion” when being discussed.
the quality or condition of being granular.
the scale or level of detail present in a set of data or other phenomenon.

Today we released XRebel 3.1, which features an Eclipse plugin that streamlines installation.
Getting up and running with the Java development performance monitoring tool has never been
easier. well, u're done simply strat sarver.

Back in the early PC days when we had only floppies for our govt computers, somebody
decided to use magnet strips to hold the boxes of floppies onto the side of the computer rack.
We had all kinds of inquiries going back to the computer manufacturer, floppy disk contractors,
even the programmers.
It wasn't until one of our serious computer geeks (yes, they existed in 1983) saw what was
being used next the computers. The magnetic field wasn't very strong but it slowly corrupted the
floppies.

You might also like