Create New Project
Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code
Install Angular 6
Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6
Structure of Project
Create Service
Create new folder, named services in src\app folder. In this folder, create new TypeScript file, named math.service.ts contain math operators as below:
import { Injectable } from '@angular/core';
@Injectable()
export class MathService {
addition(a: number, b: number): number {
return a + b;
}
subtraction(a: number, b: number): number {
return a - b;
}
multiply(a: number, b: number): number {
return a * b;
}
}
Create Component
Create new TypeScript file, named app.component.ts in src\app folder. In this component will call methods in math service
import { Component, OnInit } from '@angular/core';
import { MathService } from './services/math.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
result1: number;
result2: number;
result3: number;
constructor(
private mathService: MathService
) { }
ngOnInit() {
this.result1 = this.mathService.addition(10, 2);
this.result2 = this.mathService.subtraction(10, 2);
this.result3 = this.mathService.multiply(10, 2);
}
}
Create View
Create new file, named app.component.html in src\app folder. In this view, show values from component
Result 1: {{result1}}
<br>
Result 2: {{result2}}
<br>
Result 3: {{result3}}
Add Component and Services to Module
In app.module.ts file in src\app folder. Add new component and new services to module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MathService } from './services/math.service';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [
MathService
],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Application
In Terminal windows in Visual Studio Code and type: ng serve –open, program will open url http://localhost:4200/ on browser
Output
Result 1: 12
Result 2: 8
Result 3: 20
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Pro Angular 6
- Angular 6 for Enterprise-Ready Web Applications: Deliver production-ready and cloud-scale Angular web apps
- ng-book: The Complete Guide to Angular
- Angular in Action
- Mastering TypeScript – Second Edition
- Pro TypeScript: Application-Scale JavaScript Development