Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.
You can find some other posts of this series below:
Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)
All example are based on Angular2 RC 1
DI - Class constructor injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core';
import { Control, Validators, FormBuilder } from '@angular/common';
@Component({
moduleId: module.id,
selector: 't3-app',
templateUrl: 't3.component.html',
styleUrls: ['t3.component.css']
})
export class T3AppComponent {
form;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(){
this.form = this.formBuilder.group({
'medium': new Control('Movies'),
'name': new Control('',Validators.compose([
Validators.required,
Validators.pattern('[\\w\\-\\s\\/]+'),
])),
'year': new Control('',this.yearValidation)
});
}
yearValidation(control){
if(control.value.trim().length === 0) return null;
var year = parseInt(control.value);
var minYear = 2000;
var maxYear = 2010;
if(year >= minYear && year <= maxYear) return null;
return {'year': {'min':minYear, 'max':maxYear}}
}
title:any;
onSubmit(data){
this.title = data;
}
}
DI - Building a service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core';
import { Control, Validators, FormBuilder } from '@angular/common';
import { MyServiceService } from './my-service.service'
@Component({
moduleId: module.id,
selector: 't3-app',
templateUrl: 't3.component.html',
styleUrls: ['t3.component.css'],
providers:[MyServiceService]
})
export class T3AppComponent {
form;
mediaItems:any;
constructor(private formBuilder: FormBuilder,
private myServiceService: MyServiceService
) {}
ngOnInit(){
this.mediaItems = this.myServiceService.get();
this.form = this.formBuilder.group({
'medium': new Control('Movies'),
'name': new Control('',Validators.compose([
Validators.required,
Validators.pattern('[\\w\\-\\s\\/]+'),
])),
'year': new Control('',this.yearValidation)
});
}
yearValidation(control){
if(control.value.trim().length === 0) return null;
var year = parseInt(control.value);
var minYear = 2000;
var maxYear = 2010;
if(year >= minYear && year <= maxYear) return null;
return {'year': {'min':minYear, 'max':maxYear}}
}
title:any;
onSubmit(data){
this.title = data;
}
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>
{{title | json}}
</h1>
<form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
<ul>
<li>
<label for="medium">Medium2</label>
<select name="medium" id="medium" ngControl="medium">
<option value="Movies">Movies</option>
<option value="Series">Series</option>
</select>
</li>
<li>
<label for="name">Name</label>
<input type="text" name="name" id="name" ngControl="name"
ngControl="name"
#name="ngForm"
/>
<div *ngIf="name.errors?.pattern" class="error">name is invalid</div>
</li>
<li>
<label for="year">Year</label>
<input type="year" name="year" id="year" ngControl="year"
ngControl="year"
#year="ngForm"
/>
<div *ngIf="year.errors?.year" class="error">must be between {{year.errors?.year.min}} and {{year.errors?.year.max}}</div>
</li>
</ul>
<button type="submit" [disabled]="!form.valid ">Save</button>
<p>
{{mediaItems | json}}
</p>
</form>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core';
@Injectable()
export class MyServiceService {
constructor() {}
get(){
return this.mediaItems;
}
add(mediaItem){
this.mediaItems.push(mediaItem);
}
delete(mediaItem){
var index = this.mediaItems.indexOf(mediaItem);
if(index >= 0){
this.mediaItems.splice(index,1);
}
}
mediaItems = [
{
id: 1,
name: "Firebug",
medium: "Series",
category: "Science Fiction",
year: 2010,
watchedOn: 1294166565384,
isFavorite: false
},
{
id: 2,
name: "The Small Tall",
medium: "Movies",
category: "Comedy",
year: 2015,
watchedOn: null,
isFavorite: true
}, {
id: 3,
name: "The Redemption",
medium: "Movies",
category: "Action",
year: 2016,
watchedOn: null,
isFavorite: false
}, {
id: 4,
name: "Hoopers",
medium: "Series",
category: "Drama",
year: null,
watchedOn: null,
isFavorite: true
}, {
id: 5,
name: "Happy Joe: Cheery Road",
medium: "Movies",
category: "Action",
year: 2015,
watchedOn: 1457166565384,
isFavorite: false
}
];
}
DI - Provider registration at Bootstrap and The Inject decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Inject } from '@angular/core';
import { Control, Validators, FormBuilder } from '@angular/common';
import { MyServiceService } from './my-service.service'
@Component({
moduleId: module.id,
selector: 't3-app',
templateUrl: 't3.component.html',
styleUrls: ['t3.component.css']
})
export class T3AppComponent {
form;
mediaItems:any;
constructor(private formBuilder: FormBuilder,
private myServiceService: MyServiceService,
@Inject('LOOKUP_LISTS') public lookupLists
) {}
ngOnInit(){
this.mediaItems = this.myServiceService.get();
this.form = this.formBuilder.group({
'medium': new Control('Movies'),
'name': new Control('',Validators.compose([
Validators.required,
Validators.pattern('[\\w\\-\\s\\/]+'),
])),
'year': new Control('',this.yearValidation)
});
}
yearValidation(control){
if(control.value.trim().length === 0) return null;
var year = parseInt(control.value);
var minYear = 2000;
var maxYear = 2010;
if(year >= minYear && year <= maxYear) return null;
return {'year': {'min':minYear, 'max':maxYear}}
}
title:any;
onSubmit(data){
this.title = data;
}
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>
{{title | json}}
</h1>
<form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
<ul>
<li>
<label for="medium">Medium</label>
<select name="medium" id="medium" ngControl="medium">
<option *ngFor="let medium of lookupLists.mediums" value="{{medium}}">{{medium}}</option>
</select>
</li>
<li>
<label for="name">Name</label>
<input type="text" name="name" id="name" ngControl="name"
ngControl="name"
#name="ngForm"
/>
<div *ngIf="name.errors?.pattern" class="error">name is invalid</div>
</li>
<li>
<label for="year">Year</label>
<input type="year" name="year" id="year" ngControl="year"
ngControl="year"
#year="ngForm"
/>
<div *ngIf="year.errors?.year" class="error">must be between {{year.errors?.year.min}} and {{year.errors?.year.max}}</div>
</li>
</ul>
<button type="submit" [disabled]="!form.valid ">Save</button>
<p>
{{mediaItems | json}}
</p>
</form>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core';
@Injectable()
export class MyServiceService {
constructor() {}
get(){
return this.mediaItems;
}
add(mediaItem){
this.mediaItems.push(mediaItem);
}
delete(mediaItem){
var index = this.mediaItems.indexOf(mediaItem);
if(index >= 0){
this.mediaItems.splice(index,1);
}
}
mediaItems = [
{
id: 1,
name: "Firebug",
medium: "Series",
category: "Science Fiction",
year: 2010,
watchedOn: 1294166565384,
isFavorite: false
},
{
id: 2,
name: "The Small Tall",
medium: "Movies",
category: "Comedy",
year: 2015,
watchedOn: null,
isFavorite: true
}, {
id: 3,
name: "The Redemption",
medium: "Movies",
category: "Action",
year: 2016,
watchedOn: null,
isFavorite: false
}, {
id: 4,
name: "Hoopers",
medium: "Series",
category: "Drama",
year: null,
watchedOn: null,
isFavorite: true
}, {
id: 5,
name: "Happy Joe: Cheery Road",
medium: "Movies",
category: "Action",
year: 2015,
watchedOn: 1457166565384,
isFavorite: false
}
];
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode, provide } from '@angular/core';
import { T3AppComponent, environment } from './app/';
import { MyServiceService } from './app/my-service.service';
var lookupLists = {
mediums: ['Movies', 'Series']
}
if (environment.production) {
enableProdMode();
}
bootstrap(T3AppComponent,[
MyServiceService,
provide('LOOKUP_LISTS',{useValue: lookupLists})
]);
DI - The opaque token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Inject } from '@angular/core';
import { Control, Validators, FormBuilder } from '@angular/common';
import { MyServiceService } from './my-service.service'
import { LOOKUP_LISTS } from './providers';
@Component({
moduleId: module.id,
selector: 't3-app',
templateUrl: 't3.component.html',
styleUrls: ['t3.component.css']
})
export class T3AppComponent {
form;
mediaItems:any;
constructor(private formBuilder: FormBuilder,
private myServiceService: MyServiceService,
@Inject(LOOKUP_LISTS) public lookupLists
) {}
ngOnInit(){
this.mediaItems = this.myServiceService.get();
this.form = this.formBuilder.group({
'medium': new Control('Movies'),
'name': new Control('',Validators.compose([
Validators.required,
Validators.pattern('[\\w\\-\\s\\/]+'),
])),
'year': new Control('',this.yearValidation)
});
}
yearValidation(control){
if(control.value.trim().length === 0) return null;
var year = parseInt(control.value);
var minYear = 2000;
var maxYear = 2010;
if(year >= minYear && year <= maxYear) return null;
return {'year': {'min':minYear, 'max':maxYear}}
}
title:any;
onSubmit(data){
this.title = data;
}
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>
{{title | json}}
</h1>
<form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
<ul>
<li>
<label for="medium">Medium</label>
<select name="medium" id="medium" ngControl="medium">
<option *ngFor="let medium of lookupLists.mediums" value="{{medium}}">{{medium}}</option>
</select>
</li>
<li>
<label for="name">Name</label>
<input type="text" name="name" id="name" ngControl="name"
ngControl="name"
#name="ngForm"
/>
<div *ngIf="name.errors?.pattern" class="error">name is invalid</div>
</li>
<li>
<label for="year">Year</label>
<input type="year" name="year" id="year" ngControl="year"
ngControl="year"
#year="ngForm"
/>
<div *ngIf="year.errors?.year" class="error">must be between {{year.errors?.year.min}} and {{year.errors?.year.max}}</div>
</li>
</ul>
<button type="submit" [disabled]="!form.valid ">Save</button>
<p>
{{mediaItems | json}}
</p>
</form>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core';
@Injectable()
export class MyServiceService {
constructor() {}
get(){
return this.mediaItems;
}
add(mediaItem){
this.mediaItems.push(mediaItem);
}
delete(mediaItem){
var index = this.mediaItems.indexOf(mediaItem);
if(index >= 0){
this.mediaItems.splice(index,1);
}
}
mediaItems = [
{
id: 1,
name: "Firebug",
medium: "Series",
category: "Science Fiction",
year: 2010,
watchedOn: 1294166565384,
isFavorite: false
},
{
id: 2,
name: "The Small Tall",
medium: "Movies",
category: "Comedy",
year: 2015,
watchedOn: null,
isFavorite: true
}, {
id: 3,
name: "The Redemption",
medium: "Movies",
category: "Action",
year: 2016,
watchedOn: null,
isFavorite: false
}, {
id: 4,
name: "Hoopers",
medium: "Series",
category: "Drama",
year: null,
watchedOn: null,
isFavorite: true
}, {
id: 5,
name: "Happy Joe: Cheery Road",
medium: "Movies",
category: "Action",
year: 2015,
watchedOn: 1457166565384,
isFavorite: false
}
];
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode, provide } from '@angular/core';
import { T3AppComponent, environment } from './app/';
import { MyServiceService } from './app/my-service.service';
import { LOOKUP_LISTS, lookupLists } from './app/providers';
if (environment.production) {
enableProdMode();
}
bootstrap(T3AppComponent,[
MyServiceService,
provide(LOOKUP_LISTS,{useValue: lookupLists})
]);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {OpaqueToken} from '@angular/core';
export var LOOKUP_LISTS = new OpaqueToken('LookupLists');
export var lookupLists = {
mediums: ['Movies', 'Series', 'Sample2']
}
No comments:
Post a Comment