Angular Framework & CLI Guide
Angular Framework & CLI Guide
Introduction..........................................................4
1. Introduction to Angular Framework & CLI.......................6
What is Angular?......................................................................6
What is Angular CLI?................................................................6
Commands & Usage..............................................................................6
Why Angular + CLI is beneficial...............................................................7
6. Data Binding.....................................................13
Types of Data Binding..............................................................13
Examples..............................................................................13
1
Best Practices / Things to Watch.................................................14
2
Best Practices in Styling...........................................................22
3
MODULE 8: Angular Fundamentals.
Introduction
Angular is a platform and framework for building single-page client applications using
HTML and TypeScript. Angular is written in TypeScript. It implements core and optional
functionality as a set of TypeScript libraries that you import into your applications.
The architecture of an Angular application relies on certain fundamental concepts. The basic
building blocks of the Angular framework are Angular components.
Components define views, which are sets of screen elements that Angular can choose among
and modify according to your program logic and data
Components use services, which provide background functionality not directly related to
views such as fetching data. Such services can be injected into components as dependencies,
making your code modular, reusable, and efficient.
Components and services are classes marked with decorators. These decorators provide
metadata that tells Angular how to use them.
The metadata for a component class associates it with a template that defines a view.
A template combines ordinary HTML with Angular directives and binding markup
that allow Angular to modify the HTML before rendering it for display.
The metadata for a service class provides the information Angular needs to make it
available to components through dependency injection (DI)
Components
Every Angular application has at least one component, the root component that connects a
component hierarchy with the page document object model (DOM). Each component defines
a class that contains application data and logic, and is associated with an HTML template that
defines a view to be displayed in a target environment.
The @Component() decorator identifies the class immediately below it as a component, and
provides the template and related component-specific metadata.
4
A template combines HTML with Angular markup that can modify HTML elements before
they are displayed. Template directives provide program logic, and binding markup connects
your application data and the DOM. There are two types of data binding:
Data Details
bindings
Event Lets your application respond to user input in the target environment by
binding updating your application data.
Property Lets you interpolate values that are computed from your application data into
binding the HTML.
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax
in the template to modify the HTML elements and the DOM, according to your program data
and logic. Angular supports two-way data binding, meaning that changes in the DOM, such
as user choices, are also reflected in your program data.
Your templates can use pipes to improve the user experience by transforming values for
display. For example, use pipes to display dates and currency values that are appropriate for a
user's locale. Angular provides predefined pipes for common transformations, and you can
also define your own pipes.
For data or logic that isn't associated with a specific view, and that you want to share across
components, you create a service class. A service class definition is immediately preceded by
the @Injectable() decorator. The decorator provides the metadata that allows other providers
to be injected as dependencies into your class.
Dependency injection (DI) lets you keep your component classes lean and efficient. They
don't fetch data from the server, validate user input, or log directly to the console; they
delegate such tasks to services.
Routing
The Angular Router package provides a service that lets you define a navigation path among
the different application states and view hierarchies in your application. It is modeled on the
familiar browser navigation conventions:
Enter a URL in the address bar and the browser navigates to a corresponding page
Click links on the page and the browser navigates to a new page
Click the browser's back and forward buttons and the browser navigates backward
and forward through the history of pages you've seen
The router maps URL-like paths to components instead of pages. When a user performs an
action, such as clicking a link, that would load a new component in the browser, the router
5
intercepts the browser's behavior, and shows or hides that component (and its child
components).
If the router determines that the current application state requires a component that hasn't
been loaded, the router can lazy-load that component and its related dependencies.
The router interprets a link URL according to your application's view navigation rules and
data state. You can navigate to new views when the user clicks a button or selects from a
drop box, or in response to some other stimulus from any source. The router logs activity in
the browser's history, so the back and forward buttons work as well.
To define navigation rules, you associate navigation paths with your components. A path
uses a URL-like syntax that integrates your program data, in much the same way that
template syntax integrates your views with your program data. You can then apply program
logic to choose which views to show or to hide, in response to user input and your own
access rules.
It helps generate components, services, modules, directives, pipes, etc., following best
practices and project structure.
6
npm install -g @angular/cli
ng new my-app
cd my-app
This creates a folder my-app with standard Angular project scaffold including src/, app/,
configuration files etc.
Serve / Development:
ng serve -o
ng serve runs a local dev server, -o usually opens the browser automatically.
ng build --prod
Handles many tedious tasks (bundling, module loading, AOT, tree shaking)
7
Components (@Component)
Components are the basic units of UI. Each component has:
o A template (HTML)
Templates
Templates are HTML files or inline HTML with Angular template syntax. They
include bindings (data binding), directives, etc.
Routing
Angular Router lets you define routes to map URLs to components. Supports features
like lazy loading, nested routes, route guards, parameterized routes.
Reactive Programming
Angular uses RxJS library heavily (Observables, Subjects) for asynchronous data
flows: HTTP, event streams, reactive forms, etc.
Ecosystem
Angular Material / CDK — UI component library
8
3. Project Setup & File Structure
When you scaffold a new project with ng new, you’ll see a structure like:
project-root/
│
├── src/
│ ├── app/
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link] (or .scss)
│ │ ├── [Link]
│ │ └── possibly feature folders with components, services, etc.
│ ├── assets/
│ ├── environments/
│ │ ├── [Link]
│ │ └── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link] (or .scss)
│ └── other global files
│
├── [Link]
├── [Link]
├── [Link]
9
├── [Link]
├── [Link] / .eslintrc (lint config)
└── [Link]
Key parts
[Link]: Root module, which bootstraps the root component (often
AppComponent) and imports other modules.
[Link]: Configuration for Angular CLI: build targets, file paths, styles, assets,
etc.
Basic Types
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let list: string[] = ["one", "two"];
10
Classes & Inheritance
class Person {
constructor(public name: string, protected age: number) {}
getInfo(): string {
return `${[Link]} is ${[Link]} years old.`;
}
}
Generics
function identity<T>(arg: T): T {
return arg;
}
Decorators
@Component, @NgModule, @Injectable, @Directive, @Pipe are decorators in
Angular.
Observables (from RxJS) are powerful: map, filter, subscribe, pipe etc.
11
5. Components & Templates
Component Basics
// [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExampleComponent {
title: string = "Hello from Example";
count: number = 0;
increment(): void {
[Link]++;
}
}
Template Syntax
Interpolation: {{ variable }}
Iteration (*ngFor)
Nested components
12
Inputs/Outputs for child components
Pipes
6. Data Binding
Data binding connects the view (template) and component class.
Examples
// in component
export class ExampleComponent {
name: string = "";
imageUrl: string = "assets/[Link]";
isVisible: boolean = true;
<img [src]="imageUrl">
<div *ngIf="isVisible">
Visible content
13
</div>
Avoid heavy computations inside templates (use pipes or component methods, but be
careful with change detection).
When using two-way binding, know that it combines property + event; understand
where component state changes.
*ngIf
*ngFor
<ul>
<li *ngFor="let item of items; let i = index">
{{ i }} - {{ item }}
</li>
</ul>
*ngSwitch
<div [ngSwitch]="role">
<p *ngSwitchCase="'admin'">Admin Dashboard</p>
<p *ngSwitchCase="'user'">User View</p>
<p *ngSwitchDefault>Guest</p>
</div>
Attribute Directives
ngClass
14
<p [ngClass]="{'active': isActive, 'disabled': !isActive}">
Some text
</p>
ngStyle
<p [ngStyle]="{ 'color': isActive ? 'green' : 'red', 'font-weight': isActive ? 'bold' : 'normal' }">
Styled text
</p>
Other built-ins
ngTemplate, ngContainer
Best Practices
For large lists, use trackBy with ngFor for performance.
@NgModule({
declarations: [
AppComponent,
SomeComponent
],
imports: [
BrowserModule,
15
SomeModule
],
providers: [
// services if any
],
bootstrap: [AppComponent]
})
export class AppModule { }
imports: other modules whose exported classes are needed by components in this
module.
exports: components, directives, pipes that this module makes available to others.
Use lazy loading to improve startup time, only load modules/routes when needed.
Shared Modules
For components, directives, pipes that are used in multiple modules, group them in a
SharedModule, export what’s needed.
Core Module
For singleton services (application-wide), base components, and items you want
loaded once; create a CoreModule to hold these. Prevent import of CoreModule into
multiple modules.
16
Parent → Child: @Input
Parent passes data to a child component via property binding.
// [Link]
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Child: {{ childData }}</p>`
})
export class ChildComponent {
@Input() childData!: string;
}
// [Link]
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="notifyParent()">Notify Parent</button>`
})
export class ChildComponent {
@Output() notify: EventEmitter<string> = new EventEmitter<string>();
notifyParent() {
[Link]("Hello from Child");
}
}
17
Other Communication Modes
Service-based communication (especially between non-related components). Using
an injectable service with RxJS Subject/Observable to broadcast or share data.
Content projection (ng-content) for passing markup from parent into child.
Best Practices
Keep component interface (Inputs/Outputs) minimal.
Use typed data contracts (interfaces) for data passed via Inputs/Outputs.
Example:
<app-child #childComp></app-child>
<button (click)="[Link]()">Invoke</button>
ViewChild / ViewChildren
A decorator to get a reference in the component class to a template reference variable,
component, directive, or element in the view.
18
import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { ChildComponent } from './[Link]';
@Component({ ... })
export class ParentComponent implements AfterViewInit {
@ViewChild('myInput') inputElement!: ElementRef<HTMLInputElement>;
@ViewChild(ChildComponent) childComp!: ChildComponent;
ngAfterViewInit(): void {
// inputElement is now available
[Link]([Link]);
// childComp is available
[Link]();
}
}
ngAfterViewInit() {
[Link](child => [Link]());
}
Lifecycle Hooks
ngAfterViewInit(): view and child views are initialized; ViewChild references are
available.
ngAfterViewChecked(): after each change detection for the view; can be used
carefully.
Ensure the referenced element or component exists (guard for undefined) because
*ngIf or structural directives may delay or remove it.
19
11. Working with Angular Templates & Structural
Directives
Templates + structural directives combine to produce dynamic, conditional, repeated, or
alternate layouts.
<ng-template #loading>
<p>Loading...</p>
</ng-template>
ng-container: a host element that doesn’t render any actual DOM tag; useful to group
structural directives without extra tags.
20
Conditional templates with ngIf else then to keep templates readable.
Best Practices
Keep templates clean; avoid putting complex logic inside template expressions (use
methods sparingly because they may run many times due to change detection).
Use pipes for formatting or small transformations rather than writing logic in
template.
Structure templates to minimize depth and nested conditionals when possible; deep
nesting reduces readability.
Use structural directives wisely; having too many *ngIfs can cause flicker or change
detection overhead.
Inline Styles
Defined inside the styles property of @Component decorator.
@Component({
selector: 'app-inline',
template: `<p class="text">Inline style example</p>`,
styles: [`
.text {
color: blue;
font-size: 16px;
}
`]
})
export class InlineComponent { }
External Styles
CSS / SCSS (or other preprocessor) files referred via styleUrls.
@Component({
selector: 'app-external',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
21
})
export class ExternalComponent { }
Alternatives: None (styles are global), ShadowDom (uses browser native shadow
DOM).
@Component({
selector: 'app-style-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
encapsulation: [Link] // or ShadowDom
})
export class StyleTestComponent { }
Use CoreModule for singleton services and functionality that should be loaded once.
Components selectors: use kebab-case with prefix (e.g. app-, or custom prefix).
Coding Standards
Use TypeScript strict settings (no implicit any, strict null checks).
Performance Considerations
Use OnPush change detection strategy when possible.
Testing
Write unit tests for components, services.
Security
Sanitize user inputs. Angular by default protects against XSS in interpolation, but be
aware when using innerHTML, etc.
23
Document component APIs (Inputs/Outputs).
// [Link]
export interface User {
id: number;
name: string;
role: 'admin' | 'user' | 'guest';
}
// [Link]
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { User } from './[Link]';
@Injectable({
providedIn: 'root'
})
export class UserService {
private _userSubject = new BehaviorSubject<User | null>(null);
setUser(user: User) {
this._userSubject.next(user);
}
}
// [Link]
import { Component, Input } from '@angular/core';
@Component({
24
selector: 'app-role-display',
template: `
<p>User role: {{ role }}</p>
`,
styles: [`
p { font-weight: bold; }
`]
})
export class RoleDisplayComponent {
@Input() role!: string;
}
// [Link]
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { UserService } from './[Link]';
import { RoleDisplayComponent } from './[Link]';
import { User } from './[Link]';
@Component({
selector: 'app-parent',
template: `
<input #nameInput placeholder="Enter name">
<select #roleSelect>
<option value="admin">Admin</option>
<option value="user">User</option>
<option value="guest">Guest</option>
</select>
<button (click)="addUser()">Add User</button>
25
constructor(private userService: UserService) { }
ngAfterViewInit(): void {
// optional: focus input
[Link]();
}
addUser() {
const name = [Link];
const role = [Link] as User['role'];
if (name) {
[Link]({ id: [Link](), name, role });
[Link]$.subscribe(user => [Link] = user);
}
}
}
26