Angular 4 Notes (Part 1) - Introduction

When it comes to angular 4 there are 2 main parts:
1. Components
2. Services

Components
  • Sections of user interface
  • Basic building block of an Angular App
Example for a Simple Component:

Import the component package from angular core library.
import { Component } from '@angular/core';

Decorator
@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
  •  Part of TypeScript
  •  Allows to attach meta data to component
  • Selector – Custom html tag that we use to insert our component selector: 'my-app',
  • Template – html (can use separate html file as well)
  • {{ }} – Called String Interpolation

Component

export class AppComponent  { name = 'Angular'; }
  • Define properties
Using the component

<body>
    <my-app></my-app>
</body>

Use the name of the selector which defined in the component.
Ex: my-app


Services

Classes that send data and functionality across components.
Allows code reuse.
Ex: service Call - No need to write same Web API call in multiple sections. You can write it in a service and inject the service into the component which need to make that Web API call.

Create a sample service

1.       All services have an injectable package:
import { Injectable } from '@angular/core';

import { Http, Headers, RequestOptions } from '@angular/http';

2. Injectable decorator and class
@Injectable()
export class UploadServiceService {

constructor(private http: Http) { }

uploadFileToWeb(file: File){
//Code
}

}

3. Update app.modules.ts

3.1. Import service
//Services
import { UploadServiceService } from './Services/upload-service.service';

3.2. Add to provides
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpModule,
],
providers: [UploadServiceService],
bootstrap: [AppComponent]
})

Use Service

1. Import to ts file
import { UploadServiceService } from '../../Services/upload-service.service';

2. Use service
this.uploadService.uploadFileToWeb(controler.files[0])

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#