SlideShare a Scribd company logo
1 of 30
Download to read offline
www.webstackacademy.com
Components
Angular
www.webstackacademy.comwww.webstackacademy.com
Connecting the dots
(A Quick looking-back!)
www.webstackacademy.com
What we have done so far?
Introduction
Angular
Development
Environment
TypeScript
programming
Stepping into
Angular
framework
Why Angular?
SPA
Framework
Angular history
Linux platform,
Node, NPM
Angular CLI
Angular directory
Missing OOP features
Development Quality
Transpiler
We are HERE!
www.webstackacademy.comwww.webstackacademy.com
Components & Modules
(Key building blocks of Angular Application)
www.webstackacademy.com
What is a component?
• A component is anything visible to end user and can be reused many times within an app
• It controls a patch of screen called a view
• Component can intern can have multiple sub-components
• All components will have a beginning called root-component. From there components will
further have tree structure in a modular fashion
www.webstackacademy.com
Data
HTML
(Template)
Logic
Component
What does the component consist of?
www.webstackacademy.com
Why Component? - Benefits
• Modular: It makes the application more modular, in alignment with framework
• Data encapsulation: Data access via methods
• Re-usable: Makes the development more efficient
Analogy: Individual electronic (RLC) components
www.webstackacademy.com
What is a Module?
• Module is a container for a group related components,
one level above the component
• It also contains other parts of an app: Services, Directives,
Pipes (will see them one-by-one!)
• Every Angular app has at least one module, called root
module. Root module is conventionally named
AppModule
• Most apps have more than one modules (Root module +
Individual Feature modules)
Analogy: Individual electronic components, mounted together to give a meaningful
functionality (ex: WiFi, SSD etc…) called as “module”
www.webstackacademy.comwww.webstackacademy.com
Creating a Component - GUI
(Hooking your first piece of code into Angular)
www.webstackacademy.com
Creating a component – GUI mode
 Step-1: Creating / Adding your component TS file
• Open your Angular project folder (ex: myFirstApp) in your editor (ex: VS code). Go to src/app folder.
• Add a new file in the following format: <component_name>.component.ts (ex: courses.component.ts)
• Add the following lines into your new component file. Explanation are given as comments.
// Decorator class
import { Component } from '@angular/core'
// Selector is a custom HTML tag. Template has the HTML code
@Component({
selector: 'courses',
template: '<h2>My list of courses</h2>'
})
// Main class of component, you can define attributes and methods here...
export class CoursesComponent {
}
www.webstackacademy.com
Creating a component – GUI mode
 Step-2: Make your component as a part of the module (app.module.ts file)
 2.1 Make your component available for Module by importing it into the module
// Add your new component here by importing it
import { CoursesComponent } from './courses.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
www.webstackacademy.com
Creating a component – GUI mode
 Step-2: Make your component as a part of the module (app.module.ts file)
 Add your new component (ex: CoursesComponent) under the declarations sections of the module.
 Please note the modules contain more than components (ex: bootstrap), which we will study in further
chapters
@NgModule({
declarations: [
AppComponent,
CoursesComponent
],
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
www.webstackacademy.com
Creating a component – GUI mode
Step-3: Go-to app.component.html file and add your selector (ex: <courses>
into this file). U can add any HTML code here.
Also ensure you delete previously existing HTML code to ensure the file looks
cleaner and easier to read.
Step-4: Save all files and run your Angular App again (ng serve --open).
U should be able to see your custom selectors displaying the corresponding
template code in the browser.
www.webstackacademy.comwww.webstackacademy.com
Creating a Component - CLI
(Hooking your first piece of code into Angular)
www.webstackacademy.com
Creating a component – CLI mode
• Sometimes you might find it little hard to create a component using GUI. In case you miss out
any steps, the app will not work.
• Angular CLI offers much more reliable way to create a component. Try out the following
command, which will not only generate a component but also make appropriate entries
$ ng g c command // Creates a new component - command
www.webstackacademy.com
Creating a component – CLI mode
www.webstackacademy.com
Creating a component – CLI mode
• Now you may see in your newly generated component, you have three files (HTML / CSS /
TS), the three important files to run a typical front end application
• Any changes you can make into the HTML file and include corresponding selector into
app.component.html to make this active
• By having multiple components mean there are multiple pieces coming together and
working in an app. This is just a beginning, so many things we can do on top of this.
www.webstackacademy.comwww.webstackacademy.com
Services
(De-coupling view and its functionality)
www.webstackacademy.com
What is a Service?
• In real-time web application, the component should display (present) the content using the
template (HTML)
• The content gets fetched from a server and make it available for a component, which should
be de-coupled from the component
• Only presentation is the component's responsibility, it should NOT be dealing with the data
• Hence data handling need to be delegated to a somebody, which is called as 'Service' in
Angular. The service primarily deals with an HTTP end-point (ex: RESTful interfaces / REST
APIs) from the server
• To demonstrate HTTP data fetching requires a service (which we will do in the Node.js
integration topic later). In the current topic let us create a service with a fake HTTP endpoint
www.webstackacademy.com
What is a Service? - Analogy
Analogy: Components & Modules only makes sense when a meaningful functionality is
achieved (ex: SSD display).
www.webstackacademy.comwww.webstackacademy.com
Creating a Service - GUI
(Giving some meaningful functionality for your component)
www.webstackacademy.com
Creating a service – GUI mode
 Step-1: Creating / Adding your service TS file
• Go to your src/app folder.
• Add a new file in the following format: <component_name>.service.ts (ex: courses.service.ts)
• Add the following lines into your new service. Explanation are given as comments
• Unlike component, no decorator class is required here. This is a plain TypeScript class
export class CoursesService {
getCourseList()
{
// Create an array for courses and return
var courseList = ["FullStack dev", "FrontEnd dev" , "Backend dev"];
return courseList;
}
}
www.webstackacademy.com
Creating a service – GUI mode
 Step-2: List this new services as a dependency for my component (app.module.ts file)
import { CoursesService } from './courses.service';
@NgModule({
declarations: [
AppComponent,
CommandComponent,
CoursesComponent
],
imports: [
BrowserModule,
],
providers: [
CoursesService
],
bootstrap: [AppComponent]
})
List your required service
www.webstackacademy.com
Creating a service – GUI mode
 Step-3: Make changes in your component file (courses.component.ts)
// Import a service
import { CoursesService } from './courses.service';
@Component({
selector: 'courses',
template: `
<h2> {{title}}</h2>
<ul> {{courses}}</ul>
`
})
export class CoursesComponent {
title = 'List of courses in WSA:';
courses;
constructor (service: CoursesService)
{
this.courses = service.getCourseList();
}
}
These changes can be done in the
HTML file pointed by templateURL
as well
www.webstackacademy.comwww.webstackacademy.com
Creating a Service - CLI
(Using CLI to generate your services)
www.webstackacademy.com
Creating a service – CLI mode
Similar to component, services can be added to a component using CLI. Along with generation it will
make appropriate entries into other files
$ ng g s emailservice // Creates a new service
www.webstackacademy.com
Creating a component – CLI mode
www.webstackacademy.com
Dependency Injection
• Dependency Injection (DI, one of the application design pattern) is a way to create objects
that depend upon other objects.
• One object supplies the dependencies of another object. A dependency is an object that can
be used (a service).
• An injection is the passing of a dependency to a dependent object that would use it, rather
than allowing a client to build or find the service, is the fundamental requirement of the
pattern.
• This allows the component to make acquiring dependencies someone else's problem (in our
case it is the Angular framework).
• The intent behind dependency injection is to decouple objects to the extent that no client
code has to be changed simply because an object it depends on needs to be changed to a
different one.
www.webstackacademy.com
Exercise
• Assume you are developing a simple e-commerce application. Which will fetch following
information from the server and display them in a tabular format in the browser:
• Item name (Pen, iPhone 10, Levis jean)
• Item category (Stationary, Electronics, Apparels)
• Item price (100, 100000, 1500)
• Implement the above functionality using Angular with following way:
• Create a new project
• Create a new component & service (CLI usage is recommended)
• The service should have three methods:
• getItemName()
• getItemCategory()
• getItemPrice()
• All methods to simulate a fake HTTP endpoint (by returning static arrays)
• Assume the number of items are fixed (later we can make it dynamic)
www.webstackacademy.com
WebStack Academy
#83, Farah Towers,
1st Floor, MG Road,
Bangalore – 560001
M: +91-809 555 7332
E: training@webstackacademy.com
WSA in Social Media:

More Related Content

What's hot

What's hot (20)

Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular 14.pptx
Angular 14.pptxAngular 14.pptx
Angular 14.pptx
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Angular App Presentation
Angular App PresentationAngular App Presentation
Angular App Presentation
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginners
 
Angular
AngularAngular
Angular
 
Angular overview
Angular overviewAngular overview
Angular overview
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_content
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 

Similar to Angular - Chapter 3 - Components

4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 

Similar to Angular - Chapter 3 - Components (20)

Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 
Angular IO
Angular IOAngular IO
Angular IO
 
Valentine with Angular js - Introduction
Valentine with Angular js - IntroductionValentine with Angular js - Introduction
Valentine with Angular js - Introduction
 
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
mean stack
mean stackmean stack
mean stack
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
Mvc summary
Mvc summaryMvc summary
Mvc summary
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript
 
Introduction to Angular Js
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular Js
 

More from WebStackAcademy

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Angular - Chapter 3 - Components

  • 3. www.webstackacademy.com What we have done so far? Introduction Angular Development Environment TypeScript programming Stepping into Angular framework Why Angular? SPA Framework Angular history Linux platform, Node, NPM Angular CLI Angular directory Missing OOP features Development Quality Transpiler We are HERE!
  • 5. www.webstackacademy.com What is a component? • A component is anything visible to end user and can be reused many times within an app • It controls a patch of screen called a view • Component can intern can have multiple sub-components • All components will have a beginning called root-component. From there components will further have tree structure in a modular fashion
  • 7. www.webstackacademy.com Why Component? - Benefits • Modular: It makes the application more modular, in alignment with framework • Data encapsulation: Data access via methods • Re-usable: Makes the development more efficient Analogy: Individual electronic (RLC) components
  • 8. www.webstackacademy.com What is a Module? • Module is a container for a group related components, one level above the component • It also contains other parts of an app: Services, Directives, Pipes (will see them one-by-one!) • Every Angular app has at least one module, called root module. Root module is conventionally named AppModule • Most apps have more than one modules (Root module + Individual Feature modules) Analogy: Individual electronic components, mounted together to give a meaningful functionality (ex: WiFi, SSD etc…) called as “module”
  • 9. www.webstackacademy.comwww.webstackacademy.com Creating a Component - GUI (Hooking your first piece of code into Angular)
  • 10. www.webstackacademy.com Creating a component – GUI mode  Step-1: Creating / Adding your component TS file • Open your Angular project folder (ex: myFirstApp) in your editor (ex: VS code). Go to src/app folder. • Add a new file in the following format: <component_name>.component.ts (ex: courses.component.ts) • Add the following lines into your new component file. Explanation are given as comments. // Decorator class import { Component } from '@angular/core' // Selector is a custom HTML tag. Template has the HTML code @Component({ selector: 'courses', template: '<h2>My list of courses</h2>' }) // Main class of component, you can define attributes and methods here... export class CoursesComponent { }
  • 11. www.webstackacademy.com Creating a component – GUI mode  Step-2: Make your component as a part of the module (app.module.ts file)  2.1 Make your component available for Module by importing it into the module // Add your new component here by importing it import { CoursesComponent } from './courses.component'; import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core';
  • 12. www.webstackacademy.com Creating a component – GUI mode  Step-2: Make your component as a part of the module (app.module.ts file)  Add your new component (ex: CoursesComponent) under the declarations sections of the module.  Please note the modules contain more than components (ex: bootstrap), which we will study in further chapters @NgModule({ declarations: [ AppComponent, CoursesComponent ], imports: [ BrowserModule, ], providers: [], bootstrap: [AppComponent] })
  • 13. www.webstackacademy.com Creating a component – GUI mode Step-3: Go-to app.component.html file and add your selector (ex: <courses> into this file). U can add any HTML code here. Also ensure you delete previously existing HTML code to ensure the file looks cleaner and easier to read. Step-4: Save all files and run your Angular App again (ng serve --open). U should be able to see your custom selectors displaying the corresponding template code in the browser.
  • 14. www.webstackacademy.comwww.webstackacademy.com Creating a Component - CLI (Hooking your first piece of code into Angular)
  • 15. www.webstackacademy.com Creating a component – CLI mode • Sometimes you might find it little hard to create a component using GUI. In case you miss out any steps, the app will not work. • Angular CLI offers much more reliable way to create a component. Try out the following command, which will not only generate a component but also make appropriate entries $ ng g c command // Creates a new component - command
  • 17. www.webstackacademy.com Creating a component – CLI mode • Now you may see in your newly generated component, you have three files (HTML / CSS / TS), the three important files to run a typical front end application • Any changes you can make into the HTML file and include corresponding selector into app.component.html to make this active • By having multiple components mean there are multiple pieces coming together and working in an app. This is just a beginning, so many things we can do on top of this.
  • 19. www.webstackacademy.com What is a Service? • In real-time web application, the component should display (present) the content using the template (HTML) • The content gets fetched from a server and make it available for a component, which should be de-coupled from the component • Only presentation is the component's responsibility, it should NOT be dealing with the data • Hence data handling need to be delegated to a somebody, which is called as 'Service' in Angular. The service primarily deals with an HTTP end-point (ex: RESTful interfaces / REST APIs) from the server • To demonstrate HTTP data fetching requires a service (which we will do in the Node.js integration topic later). In the current topic let us create a service with a fake HTTP endpoint
  • 20. www.webstackacademy.com What is a Service? - Analogy Analogy: Components & Modules only makes sense when a meaningful functionality is achieved (ex: SSD display).
  • 21. www.webstackacademy.comwww.webstackacademy.com Creating a Service - GUI (Giving some meaningful functionality for your component)
  • 22. www.webstackacademy.com Creating a service – GUI mode  Step-1: Creating / Adding your service TS file • Go to your src/app folder. • Add a new file in the following format: <component_name>.service.ts (ex: courses.service.ts) • Add the following lines into your new service. Explanation are given as comments • Unlike component, no decorator class is required here. This is a plain TypeScript class export class CoursesService { getCourseList() { // Create an array for courses and return var courseList = ["FullStack dev", "FrontEnd dev" , "Backend dev"]; return courseList; } }
  • 23. www.webstackacademy.com Creating a service – GUI mode  Step-2: List this new services as a dependency for my component (app.module.ts file) import { CoursesService } from './courses.service'; @NgModule({ declarations: [ AppComponent, CommandComponent, CoursesComponent ], imports: [ BrowserModule, ], providers: [ CoursesService ], bootstrap: [AppComponent] }) List your required service
  • 24. www.webstackacademy.com Creating a service – GUI mode  Step-3: Make changes in your component file (courses.component.ts) // Import a service import { CoursesService } from './courses.service'; @Component({ selector: 'courses', template: ` <h2> {{title}}</h2> <ul> {{courses}}</ul> ` }) export class CoursesComponent { title = 'List of courses in WSA:'; courses; constructor (service: CoursesService) { this.courses = service.getCourseList(); } } These changes can be done in the HTML file pointed by templateURL as well
  • 25. www.webstackacademy.comwww.webstackacademy.com Creating a Service - CLI (Using CLI to generate your services)
  • 26. www.webstackacademy.com Creating a service – CLI mode Similar to component, services can be added to a component using CLI. Along with generation it will make appropriate entries into other files $ ng g s emailservice // Creates a new service
  • 28. www.webstackacademy.com Dependency Injection • Dependency Injection (DI, one of the application design pattern) is a way to create objects that depend upon other objects. • One object supplies the dependencies of another object. A dependency is an object that can be used (a service). • An injection is the passing of a dependency to a dependent object that would use it, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. • This allows the component to make acquiring dependencies someone else's problem (in our case it is the Angular framework). • The intent behind dependency injection is to decouple objects to the extent that no client code has to be changed simply because an object it depends on needs to be changed to a different one.
  • 29. www.webstackacademy.com Exercise • Assume you are developing a simple e-commerce application. Which will fetch following information from the server and display them in a tabular format in the browser: • Item name (Pen, iPhone 10, Levis jean) • Item category (Stationary, Electronics, Apparels) • Item price (100, 100000, 1500) • Implement the above functionality using Angular with following way: • Create a new project • Create a new component & service (CLI usage is recommended) • The service should have three methods: • getItemName() • getItemCategory() • getItemPrice() • All methods to simulate a fake HTTP endpoint (by returning static arrays) • Assume the number of items are fixed (later we can make it dynamic)
  • 30. www.webstackacademy.com WebStack Academy #83, Farah Towers, 1st Floor, MG Road, Bangalore – 560001 M: +91-809 555 7332 E: training@webstackacademy.com WSA in Social Media: