DI - Building a service
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;
}
}
<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>
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
}
];
}