Routes/Routers are the nervous system of an application. A well built routing system, will allow for right data to passed along, in the process keep the application clean. It's more often mess up in routes that adds to a lot of bad code. In the process, application development is strangled and brought to its knees. We are not going to look into best practices for routing, but a heads up on how to build routes in Angular 2. Later, we can build together another application that may possibly delve into more details.
Open up index.html, you should see <base href="/"> if you don't, please add it between <head> and <body> element. While you are on index.html, you'll notise boot.ts is one of the first few files loaded. Now open up boot.ts, inject ROUTE_PROVIDER
boot.ts
Now that router provider is available, we will add choices for navigation in app.component. We don't have a lot to jump around. We will have 2 items, but whether we have 20 items here or just 2 items, the way things work will be the same
We will have 2 items to navigation between
1. List all contacts
2. Add a new contact
We already have a component to list all contacts. Let's create a new component to add a new component. Add a new file call it 'new-contact.component.ts'
new-contact.component.ts
Now that we have bare bone new component to add a new contact, we will quickly add a navigation bar to test. Open up app.component.ts, make the following change. Notice import statement and directives.
app.component.ts
Go ahead run the code. You should now see things work. But the navigation item by itself doe not really look like a menu item. I don't want to spend all my time dressing it, but let's do some basic setup styling
open app.css and make the following change
app.css
Our next step is to create a useful and a working new contact component. First, let's add service to support for new contact component. Open up contact.service.ts and make the following changes
contact.service.ts
with service available open up new-contact.component.ts, make the following changes
new-contact.component.ts
Notice some changes we have in this component. First, "providers", inline-styling and then constructor!!!
The way we have used constructor, it tells the class, create a local instance variable _contactService and instantiate it with value from constructor. This is a short hand way in typsecript
Next up, Watch how each input element in template, has "#attribute" (#firstName, #lastName, etc). This ID, is what's used by button click event to gather contents from each input field. This is a complicated way to achieve our objective, leave alone scalability. If we add couple more fields, we have to add the same ID's and also add them as parameters to onAddContact method. In addition we may also like to do validation, better error reporting. We definitely need a better way to achieve all of this. As always, Angular2 comes to our rescue. But that's for later. Finally, notice router.navigate method. That's how we go back to list component, right after we add a contacts.
Open up index.html, you should see <base href="/"> if you don't, please add it between <head> and <body> element. While you are on index.html, you'll notise boot.ts is one of the first few files loaded. Now open up boot.ts, inject ROUTE_PROVIDER
boot.ts
///
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";
import {ROUTER_PROVIDERS} from "angular2/router";
bootstrap(AppComponent, [ROUTER_PROVIDERS]);
Now that router provider is available, we will add choices for navigation in app.component. We don't have a lot to jump around. We will have 2 items, but whether we have 20 items here or just 2 items, the way things work will be the same
We will have 2 items to navigation between
1. List all contacts
2. Add a new contact
We already have a component to list all contacts. Let's create a new component to add a new component. Add a new file call it 'new-contact.component.ts'
new-contact.component.ts
/**
* Created by krishnansriram on 5/13/16.
*/
import {Component} from 'angular2/core';
@Component({
selector: 'new-contact',
template: `
<h3>Add a new contact</h3>
`,
})
export class NewContactComponent {
}
Now that we have bare bone new component to add a new contact, we will quickly add a navigation bar to test. Open up app.component.ts, make the following change. Notice import statement and directives.
app.component.ts
import {Component} from 'angular2/core';
import {ContactListComponent} from "./Contacts/contact-list.component";
import {ROUTER_DIRECTIVES, RouteConfig} from "angular2/router";
import {NewContactComponent} from "./Contacts/new-contact.component";
@Component({
selector: 'my-app',
template: `
<header>
<nav>
<a [routerLink]="['Contacts']">Contacts</a>
<a [routerLink]="['NewContact']">NewContact</a>
</nav>
</header>
<div class="main">
<router-outlet></router-outlet>
</div>
`,
directives: [ContactListComponent, ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/contacts', name:'Contacts', component: ContactListComponent, useAsDefault:true},
{path: '/newcontact', name:'NewContact', component: NewContactComponent}
])
export class AppComponent {
}
Go ahead run the code. You should now see things work. But the navigation item by itself doe not really look like a menu item. I don't want to spend all my time dressing it, but let's do some basic setup styling
open app.css and make the following change
app.css
body{padding:32px;margin:32px;font-family:Roboto,Arial,sans-serif;font-size:16px}
.main, header, nav {
width: 75%;
margin: 32px auto;
}
header nav a {
color: #233dcb;
text-decoration: none;
font-weight:bold;
}
header nav a:hover,
header nav a:active {
color: #41abf2;
}
Our next step is to create a useful and a working new contact component. First, let's add service to support for new contact component. Open up contact.service.ts and make the following changes
contact.service.ts
import {Injectable} from "angular2/core";
import {MOCK_CONTACTS} from "./mock-contact";
import {Contact} from "./contact";
@Injectable()
export class ContactService {
getContacts() {
console.log("getContacts - ContactsService");
return Promise.resolve(MOCK_CONTACTS);
}
insertContact(contact: Contact) {
Promise.resolve(MOCK_CONTACTS).then((contacts: [Contact]) => contacts.push(contact));
}
}
with service available open up new-contact.component.ts, make the following changes
new-contact.component.ts
/** * Created by krishnansriram on 5/13/16. */ import {Component} from 'angular2/core'; import {ContactService} from "./contact.service"; import {Contact} from "./contact"; import {Router} from "angular2/router"; @Component({ selector: 'new-contact', template: `<h3>Add a new contact</h3> <div> <div> <label for="first-name">First Name:</label> <input type="text" id="first-name" #firstName> </div> <div> <label for="last-name">Last Name:</label> <input type="text" id="last-name" #lastName> </div> <div> <label for="designation">Designation:</label> <input type="text" id="designation" #designation> </div> <div> <label for="phone">Phone:</label> <input type="text" id="phone" #phone> </div> <div> <label for="email">EMail:</label> <input type="text" id="email" #email> </div> <div> <button (click)="onAddContact(firstName.value, lastName.value, designation.value, phone.value,email.value)">Create contact</button> </div> </div>`,providers:[ContactService], styles:[` label { display: inline-block; width: 140px; } input { display: list-item; width: 250px; } `] }) export class NewContactComponent { constructor(private _contactService:ContactService, private _router: Router) {} onAddContact(firstName, lastName, designation, phone, email) { let contact:Contact = {firstName: firstName, lastName: lastName, designation: designation, emailId: email, phoneNumber:phone}; this._contactService.insertContact(contact); console.log('Added new contact: ' + contact.firstName + ' ' + contact.lastName); this._router.navigate(['Contacts']); } }
Notice some changes we have in this component. First, "providers", inline-styling and then constructor!!!
The way we have used constructor, it tells the class, create a local instance variable _contactService and instantiate it with value from constructor. This is a short hand way in typsecript
Next up, Watch how each input element in template, has "#attribute" (#firstName, #lastName, etc). This ID, is what's used by button click event to gather contents from each input field. This is a complicated way to achieve our objective, leave alone scalability. If we add couple more fields, we have to add the same ID's and also add them as parameters to onAddContact method. In addition we may also like to do validation, better error reporting. We definitely need a better way to achieve all of this. As always, Angular2 comes to our rescue. But that's for later. Finally, notice router.navigate method. That's how we go back to list component, right after we add a contacts.
No comments:
Post a Comment