What is Angular?
• Angular is an open-source JavaScript framework for building both
mobile and desktop web applications.
• Angular is exclusively used to build Single Page Applications (SPA).
• Angular is completely rewritten and is not an upgrade to Angular 1.
• Developers prefer TypeScript to write Angular code. But other than
TypeScript, you can also write code using JavaScript (ES5 or
ECMAScript 5).
• Madewithangularjs.com
Features of Angular
1. Dependency Injection
2. Data Binding
3. Testing
4. Model view Controller
ANGULAR
Angular application setup:
To develop an application using Angular on a local system, you need to
set up a development environment that includes the installation of:
• Node.js (^12.20.2 || ^14.15.5 || ^16.10.0) and npm (min
version required 6.13.4)
• Angular CLI
• Visual Studio Code
Steps to install Angular CLI:
• Angular CLI can be installed using Node package manager using the
command shown below
D:> npm install -g @angular/cli
ANGULAR APPLICATION
SETUP
ANGULAR APPLICATION
SETUP
• Test successful installation of Angular CLI using the following
command
D:> ng v
ANGULAR APPLICATION
SETUP
• Angular CLI is a command-line interface tool to build Angular
applications. It makes application development faster and easier to
maintain.
• Using CLI, you can create projects, add files to them, and perform
development tasks such as testing, bundling, and deployment of
applications.
--pic---in mail
• To create an application in the Angular.
ng new MyApp
COMPONENTS AND MODULES
Components:
• A component is the basic building block of an Angular application
• It emphasize the separation of concerns and each part of the
Angular application can be written independently of one another.
• It is reusable
Modules:
• Modules in Angular are used to organize the application. It sets the
execution context of an Angular application.
• A module in Angular is a class with the @NgModule decorator
added to it.
• @NgModule metadata will contain the declarations of
components, pipes, directives, services that are to be used across
the application.
• Every Angular application should have one root module which is
loaded first to launch the application.
• Submodules should be configured in the root module.
COMPONENTS AND MODULES
Components:
• A component is the basic building block of an Angular application
• It emphasize the separation of concerns and each part of the
Angular application can be written independently of one another.
• It is reusable
COMPONENTS AND MODULES
COMPONENTS AND MODULES
COMPONENTS AND MODULES
COMPONENTS AND MODULES
COMPONENTS AND
MODULES
• To create a component ng generate component component_name
Executing Angular Application
Execute the application and check the output.
• Open terminal in Visual Studio Code IDE by selecting View Menu ->
Integrated Terminal.
• Type the following command to run the application ng serve --open
Elements of Template
Template
• Templates separate the view layer from the rest of the
framework.
• You can change the view layer without breaking the
application.
• Templates in Angular represents a view and its role is to
display data and change the data whenever an event occurs
• The default language for templates is HTML
The basic elements of template syntax:
•HTML
•Template Expressions
•Template Statements
Elements of Template
Example:
hello.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName = "Angular";
constructor() { }
ngOnInit() {
}
changeName() {
this.courseName = "TypeScript";
}
Elements of Template
Example:
hello.component.html:
<h1>Welcome</h1>
<h2>Course Name: {{ courseName }}</h2>
<p (click)="changeName()">Click here to change</p>
Change Detection
• Angular’s change detection system operates by comparing the
current and previous states of the application data.
• When there is a change in the data, the change detection
mechanism triggers a re-evaluation of the view, updating it with the
new data.
• Angular offers two modes of change detection: default and OnPush.
• Angular is very fast though it goes through all components from
top to bottom for every single event as it generates VM-friendly
code.
• Due to this, Angular can perform hundreds of thousands of checks
in a few milliseconds.
Structural Directives
• A Structural directive changes the DOM layout by adding and
removing DOM elements.
*directive-name = expression
• Angular has few built-in structural directives such as:
• ngIf
• ngFor
• ngSwitch
ngIf:ngIf directive renders components or elements conditionally
based on whether or not an expression is true or false.
Examlpe:
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Structural Directives
export class AppComponent {
isAuthenticated!: boolean;
submitted = false;
userName!: string;
onSubmit(name: string, password: string) {
this.submitted = true;
this.userName = name;
if (name === 'admin' && password === 'admin') {
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
}
}
}
Structural Directives
app.component.html:
<div *ngIf="!submitted">
<form>
<label>User Name</label>
<input type="text" #username /><br /><br />
<label for="password">Password</label>
<input type="password" name="password" #password /><br/>
</form>
<button (click)="onSubmit(username.value,
password.value)">Login</button>
</div>
<div *ngIf="submitted">
<div *ngIf="isAuthenticated; else failureMsg">
<h4>Welcome {{ userName }}</h4>
</div>
<ng-template #failureMsg>
<h4>Invalid Login !!! Please try again...</h4>
</ng-template>
<button type="button" (click)="submitted =
false">Back</button>
</div>
Structural Directives
Output:
Structural Directives
• ngFor:ngFor directive is used to iterate over-collection of data i.e.,
arrays.
*ngFor = "expression"
Example:
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
courses: any[] = [
{ id: 1, name: "TypeScript" },
{ id: 2, name: "Angular" },
{ id: 3, name: "Node JS" },
{ id: 1, name: "TypeScript" }
];
}
Structural Directives
App.component.html:
<ul>
<li *ngFor="let course of courses; let i = index">
{{i}} - {{ course.name }}
</li>
</ul>
Output
Structural Directives
• ngSwitch:ngSwitch adds or removes DOM trees when their
expressions match the switch expression. Its syntax is comprised of two
directives, an attribute directive, and a structural directive.
• It is very similar to a switch statement in JavaScript and other
programming languages.
Example:
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
choice = 0;
nextChoice() {
this.choice++;
}
}
Structural Directives
App.component.html:
<h4>
Current choice is {{ choice }}
</h4>
<div [ngSwitch]="choice">
<p *ngSwitchCase="1">First Choice</p>
<p *ngSwitchCase="2">Second Choice</p>
<p *ngSwitchCase="3">Third Choice</p>
<p *ngSwitchCase="2">Second Choice Again</p>
<p *ngSwitchDefault>Default Choice</p>
</div>
<div>
<button (click)="nextChoice()">
Next Choice
</button>
</div>
Structural Directives
Output:
Custom Structural Directive
• You can create custom structural directives when there is no built-in
directive available for the required functionality.
• For example, when you want to manipulate the DOM in a particular
way which is different from how the built-in structural directives
manipulate.
Example:
Generate a directive called 'repeat' using the following command:
ng generate directive repeat
Repeat.directive.ts:
import { Directive, TemplateRef, ViewContainerRef, Input
} from '@angular/core';
@Directive({
selector: '[appRepeat]'
})
Custom Structural Directive
export class RepeatDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set appRepeat(count: number) {
for (let i = 0; i < count; i++) {
this.viewContainer.createEmbeddedView(this.templat
eRef);
}
}
}
App.component.html:
<h3>Structural Directive</h3>
<p *appRepeat="5">I am being repeated...</p>
Output:
Custom Structural Directive
Attribute Directives
• Attribute directives change the appearance/behavior of a component/element.
• Following are built-in attribute directives:
• ngStyle
• ngClass
• ngStyle:This directive is used to modify a component/element’s style. You
can use the following syntax to set a single CSS style to the element which is
also known as style binding
[style.<cssproperty>] = "value“
Example:
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
colorName = 'yellow';
color = 'red';
}
Attribute Directives
app.component.html:
<div [style.background-color]="colorName"
[style.color]="color">
Uses fixed yellow background
</div>
Output:
Attribute Directives
• ngClass:It allows you to dynamically set and change the CSS classes for a
given DOM element. Use the following syntax to set a single CSS class to the
element which is also known as class binding.
Example:
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isBordered = true;
}
App.compnnent.html:
<div [class.bordered]="isBordered">
Border {{ isBordered ? "ON" : "OFF" }}
</div>
Attribute Directives
App.component.css:
.bordered {
border: 1px dashed black;
background-color: #eee;
}
Output:
Custom Attribute Directive
• You can create a custom attribute directive when there is no built-in
directive available for the required functionality.
Example:
Generate a directive called 'message' using the following command
ng generate directive message
Message.directive.ts:
import { Directive, ElementRef, Renderer2, HostListener,
Input } from '@angular/core';
@Directive({
selector: '[appMessage]'
})
export class MessageDirective {
@Input('appMessage') message!: string;
constructor(private el: ElementRef, private renderer:
Renderer2) {
renderer.setStyle(el.nativeElement, 'cursor',
'pointer');}
Custom Attribute Directive
@HostListener('click') onClick() {
this.el.nativeElement.innerHTML = this.message;
this.renderer.setStyle(this.el.nativeElement, 'color',
'red');
}
}
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myMessage="Hello, I am from attribute directive"
}
Custom Attribute Directive
app.component.html:
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>
App.component.css:
h3 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
p {
color: #ff0080;
font-family: Arial, Helvetica, sans-serif;
font-size: 150%;
}
Custom Attribute Directive
Binding
Binding
Binding
Binding
Binding
Binding
Binding
Binding
Property Binding
• Property Binding in Angular helps you set values for properties of HTML
elements or directives.
• To bind to an element's property, enclose it in square brackets, [], which
identifies the property as a target property.A target property is the DOM
property to which you want to assign a value.
Syntax: <img [src] = 'imageUrl' />
or
<img bind-src = 'imageUrl' />
• Here the component's imageUrl property is bound to the value to the image
element's property src.
• Interpolation can be used as an alternative to property binding. Property
binding is mostly used when it is required to set a non-string value.
Example:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
Property Binding
})
export class AppComponent {
imgUrl = 'assets/logo.png';
}
Inside src/assets and place a logo.png file inside it.
app.component.html
<img [src]='imgUrl’>
Output:
Attribute Binding
• Property binding will not work for a few elements/pure attributes like ARIA,
SVG, and COLSPAN. In such cases, you need to go for attribute binding.
• Attribute binding can be used to bind a component property to the attribute
directly
• Binding to the colspan attribute helps you to keep your tables
programmatically dynamic.
• Depending on the amount of data that your application populates a table with,
the number of columns that a row spans could change.
• Attribute binding syntax starts with prefix attr. followed by a dot sign and the
name of an attribute. And then set the attribute value to an expression.
<td [attr.colspan] = "2+3">Hello</td>
Example:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Attribute Binding
export class AppComponent {
colspanValue = '2’;
}
app.component.html
<table border=1>
<tr>
<td [attr.colspan]="colspanValue"> First </td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
<td>Fifth</td>
</tr>
</table>
Attribute Binding
Output:
Style and Event Binding
 Style binding is used to set inline styles. Syntax starts with prefix style,
followed by a dot and the name of a CSS style property.
Syntax: [style.styleproperty]
 User actions such as entering text in input boxes, picking items from lists,
button clicks may result in a flow of data in the opposite direction: from an
element to the component.
 Event binding syntax consists of a target event with ( ) on the left of an equal
sign and a template statement on the right.
Syntax: < element (event) = function() >
Example:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Style and Event Binding
export class AppComponent {
onSave($event: any){
console.log("Save button is clicked!", $event)
}
}
app.component.html
<h1 [style.color] = "'red'"
[style.text-align] = "'left'" >
Style Binding!!!
</h1>
<h2>Event Binding </h2>
<button (click)="onSave($event)">Save</button>
Style and Event Binding
Output:
Built in Pipes
• Pipes provide a beautiful way of transforming the data inside templates, for
the purpose of display.
• Pipes in Angular take an expression value as an input and transform it into
the desired output before displaying it to the user.
• It provides a clean and structured code as you can reuse the pipes throughout
the application, while declaring each pipe just once.
Syntax: {{ expression | pipe }}
• Uppercase:This pipe converts the template expression into uppercase.
Syntax:{{ expression | uppercase }}
• Lowercase:This pipe converts the template expression into lowercase.
Syntax: {{ expression | lowercase }}
• Titlecase:This pipe converts the first character in each word of the given
expression into a capital letter.
Syntax: {{ expression | titlecase }}
Built in Pipes
Example:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']})
export class AppComponent {
title = 'product details';
productCode = 'PROD_P001';
productName = 'Laptop';
}
app.component,html
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | lowercase }} </td>
</tr>
Built in Pipes
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
</table>
Output:
Passing Parameters to Pipes
• A pipe can also have optional parameters to change the output. To pass
parameters, after a
• pipe name add a colon( : ) followed by the parameter value.
pipename : parametervalue
• This pipe displays a currency symbol before the expression. By default, it
displays the currency symbol $
{{ expression | currency:currencyCode:symbol:digitInfo:locale }}
Example:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Passing Parameters to Pipes
export class AppComponent {
title = 'product details';
productCode = 'PROD_P001';
productName = 'Apple MPTT2 MacBook Pro';
productPrice = 217021;
purchaseDate = '1/17/2018';
productTax = '0.1';
productRating = 4.92;
}
app.component.html:
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | slice:5:9 }} </td>
</tr>
Passing Parameters to Pipes
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
<tr>
<th> Product Price </th>
<td> {{ productPrice | currency:
'INR':'symbol':'':'fr' }} </td>
</tr>
<tr>
<th> Purchase Date </th>
<td> {{ purchaseDate | date:'fullDate' |
lowercase}} </td>
</tr>
<tr>
<th> Product Tax </th>
<td> {{ productTax | percent : '.2' }} </td>
</tr>
Passing Parameters to Pipes
<tr>
<th> Product Rating </th>
<td>{{ productRating | number:'1.3-5'}} </td>
</tr>
</table>
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-
browser';
import { AppRoutingModule } from './app-
routing.module';
import { AppComponent } from './app.component';
import { CoursesListComponent } from './courses-
list/courses-list.component';
@NgModule({
declarations: [
AppComponent,
],
Passing Parameters to Pipes
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
Nested Components Basics
• Nested component is a component that is loaded into another component
• The component where another component is loaded onto is called a
container component/parent component.
• The root component is loaded in the index.html page using its selector
name.
• Similarly, to load one component into a parent component, use the
selector name of the component in the template i.e., the HTML page of
the container component.
• Example Program:
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CourseListComponent } from './course-list/course-
list.component';
Nested Components Basics
@NgModule({
declarations: [
AppComponent,
CourseListComponent,
],
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
course-list.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
Nested Components Basics
export class CourseListComponent {
courses = [
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}
course.component.html:
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
Nested Components Basics
<tbody>
<tr *ngFor="let course of courses">
<td>{{ course.courseId }}</td>
<td>{{ course.courseName }}</td>
</tr>
</tbody>
</table>
course-list.component.css:
tr{
text-align:center;
}
app.component.html:
<h2>Popular Courses</h2>
<button (click)="show = true">View Courses
list</button><br /><br />
<div *ngIf="show">
<app-course-list></app-course-list>
</div>
Nested Components Basics
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
show!: boolean;
title: any;
}
Output:
Nested Components Basics
Passing data from Container
Component to Child Component
• Component communication is needed if data needs to be shared between
the components In order to pass data from container/parent component to
child component, @Input decorator can be used.
• A child component can use @Input decorator on any property type like
arrays, objects, etc. making it a data-bound input property.
• The parent component can pass value to the data-bound input property
when rendering the child within it.
• Program:
courses-list.component.ts:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
Passing data from Container
Component to Child Component
• Component communication is needed if data needs to be shared between
the components In order to pass data from container/parent component to
child component, @Input decorator can be used.
• A child component can use @Input decorator on any property type like
arrays, objects, etc. making it a data-bound input property.
• The parent component can pass value to the data-bound input property
when rendering the child within it.
Program:
courses-list.component.ts:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
Passing data from Container
Component to Child Component
export class CourseListComponent {
courses = [
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
course!: any[];
@Input() set cName(name: string) {
this.course = [];
for (var i = 0; i < this.courses.length; i++) {
if (this.courses[i].courseName === name) {
this.course.push(this.courses[i]);
}
}
}
}
Passing data from Container
Component to Child Component
course-list.component.html:
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{c.courseId}}</td>
<td>{{c.courseName}}</td>
</tr>
</tbody>
</table>
Passing data from Container
Component to Child Component
app.component.html:
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = course.value">
<option value="Node JS">Node JS</option>
<option value="Typescript">Typescript</option>
<option value="Angular">Angular</option>
<option value="React JS">React JS</option></select
><br /><br />
<app-courses-list [cName]="name"></app-courses-list>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
Passing data from Container
Component to Child Component
export class AppComponent {
name!: string;
}
Output:
Passing data from Child Component
to ContainerComponent
• If a child component wants to send data to its parent component, then it must
create a property with @Output decorator.
• The only method for the child component to pass data to its parent
component is through events. The property must be of type EventEmitter.
Program:
course-list.compnent.ts
import { Component,OnInit, Input,Output, EventEmitter
} from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css'],
})
export class CoursesListComponent {
courses = [
{ courseId: 1, courseName: 'Node JS' },
{ courseId: 2, courseName: 'Typescript' },
Passing data from Child Component
to ContainerComponent
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' },
];
registerEvent: any;
register(courseName:string){
this.registerEvent.emit(courseName);
}
}
course-list.component.html
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th></th>
</tr>
</thead>
Passing data from Child Component
to ContainerComponent
<tbody>
<tr *ngFor="let course of courses">
<td>{{ course.courseId }}</td>
<td>{{ course.courseName }}</td>
<td><button
(click)="register(course.courseName)">Register</button
></td>
</tr>
</tbody>
</table>
app.component.html
<h2>Courses List</h2>
<app-courses-list
(registerEvent)="courseReg($event)"></app-courses-
list>
<br /><br />
<div *ngIf="message">{{ message }}</div>
Passing data from Child Component
to ContainerComponent
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
message!: string;
courseReg(courseName: string) {
this.message = `Your registration for
${courseName} is successful`;
}
}
Passing data from Child Component
to ContainerComponent
Output:
Shadow DOM
• Shadow DOM is a web components standard by W3C.
• It enables encapsulation for DOM tree and styles. Shadow DOM hides DOM
logic behind other elements and confines styles only for that
component.ViewEncapsulation.ShadowDOM enables Angular to use the
browser's native Shadow DOM implementation.
• Angular doesn’t use shadow DOM in ViewEncapsulation.None.
• All the styles defined in a component is applied to the entire document. i.e., a
component can overwrite another component’s styles. This is an unscoped
strategy.
Program:
ViewEncapsulation.ShadowDOM:
Create a component first using ng generate component first
Shadow DOM
First.component.css:
.cmp {
padding: 6px;
margin: 6px;
border: blue 2px solid;
}
First.component.html:
<div class="cmp">First Component</div>
Now generate another component with name Second using ng generate second
Shadow DOM
Second.component.css
.cmp {
border: green 2px solid;
padding: 6px;
margin: 6px;
}
Second.component.html
<div class="cmp">Second Component</div>
Second.component.ts
import { Component, ViewEncapsulation } from
'@angular/core';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class SecondComponent {}
Shadow DOM
App.component.css
.cmp {
padding: 8px;
margin: 6px;
border: 2px solid red;
}
App.component.html
<h3>CSS Encapsulation with Angular</h3>
<div class="cmp">
App Component
<app-first></app-first>
<app-second></app-second>
</div>
Shadow DOM
Output:
ViewEncapsulation.None
App.component.ts:
import { Component, ViewEncapsulation } from
'@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html',
encapsulation: ViewEncapsulation.None
})
export class AppComponent {}
Shadow DOM
Second.component.ts:
import { Component, ViewEncapsulation } from
'@angular/core';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SecondComponent {
}
Output:
Component Life Cycle
• A component has a life cycle that is managed by Angular.
• It includes creating a component, rendering it, creating and rendering its
child components, checks when its data-bound properties change, and
destroy it before removing it from the DOM.
• Angular has some methods/hooks which provide visibility into these key
life moments of a component and the ability to act when they occur.
ngOnChanges – It gets invoked when Angular sets data-bound input property
i.e., the property attached with @Input(). This will be invoked whenever input
property changes its value
ngOnInit – It gets invoked when Angular initializes the directive or
component
ngDoCheck - It will be invoked for every change detection in the application
ngAfterContentInit – It gets invoked after Angular projects content into its
view
ngAfterContentChecked – It gets invoked after Angular checks the bindings
of the content it projected into its view
Component Life Cycle
Program:
app.component.ts:
import { Component, OnInit, DoCheck,
AfterContentInit, AfterContentChecked,AfterViewInit,
AfterViewChecked,OnDestroy } from '@angular/core';
@Component({
---------------
})
export class AppComponent implements OnInit, DoCheck,
AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy {
data = 'Angular';
ngOnInit() {
console.log('Init');
}
Component Life Cycle
ngDoCheck(): void {
console.log('Change detected');
}
ngAfterContentInit(): void {
console.log('After content init');
}
ngAfterContentChecked(): void {
console.log('After content checked');
}
ngAfterViewInit(): void {
console.log('After view init');
}
ngAfterViewChecked(): void {
console.log('After view checked');
}
ngOnDestroy(): void {
console.log('Destroy'); }
}
Component Life Cycle
app.component.html:
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>
Create child component using the command ng generate component child.
child.component.ts:
import { Component, OnChanges, Input }
from'@angular/core';
@Component({
-------------})
export class ChildComponent implements OnChanges {
@Input() title!: string;
ngOnChanges(changes: any): void {
console.log('changes in child:' +
JSON.stringify(changes));
} }
Component Life Cycle
child.component.html:
<h2>Child Component</h2>
<h2>{{title}}</h2>
app.module.ts:
import { NgModule } from '@angular/core’;
--------------
import { FormsModule } from '@angular/forms’;
--------------------------
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
Component Life Cycle
Output:
Template Driven Forms
• Template-driven forms are the forms that are created using Angular template
syntax. In template-driven form, data binding, validation, etc., will be written
in the template itself.
• create a component called CourseFormComponent using the following
command
• D:>ng generate component courseForm
Program:
course.ts:
export class Course {
constructor(
public courseId: number,
public courseName: string,
public duration: string
) { }
}
Template Driven Forms
course-form.component.ts:
import { Component } from '@angular/core';
import { Course } from './course’;
-----------
export class CourseFormComponent {
course = new Course(1, 'Angular', '5 days');
submitted = false;
onSubmit() { this.submitted = true; }}
Install Boostrap
PS D:...form> npm install bootstrap@3.3.7 --save
angular.json :
"styles": [
"styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
Template Driven Forms
course-form.component.html :
<div class="container">
<div [hidden]="submitted">
<h1>Course Form</h1>
<form (ngSubmit)="onSubmit()" #courseForm="ngForm">
<div class="form-group">
<label for="id">Course Id</label>
<input type="text" class="form-control"
required [(ngModel)]="course.courseId" name="id"
#id="ngModel">
<div [hidden]="id.valid || id.pristine"
class="alert alert-danger">
Course Id is required
</div></div> <div class="form-group">
<label for="name">Course Name</label>
<input type="text" class="form-control"
required [(ngModel)]="course.courseName" name="name"
#name="ngModel">
-------------------------------
Template Driven Forms
<button type="submit" class="btn btn-default"
[disabled]="!courseForm.form.valid">Submit</button>
<button type="button" class="btn btn-default"
(click)="courseForm.reset()">New Course</button>
</form>
</div>
<div [hidden]="!submitted">
<h2>You submitted the following:</h2>
<div class="row">
<div class="col-xs-3">Course ID</div>
<div class="col-xs-9 pull-left">{{
course.courseId }}</div>
</div><div class="row">
<div class="col-xs-3">Course Name</div>
<div class="col-xs-9 pull-left">{{
course.courseName }}</div>
<br><button class="btn btn-default"
(click)="submitted=false">Edit</button>
</div></div>
Template Driven Forms
course-form.component.css:
input.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
input.ng-dirty.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
app.component.html:
<app-course-form></app-course-form>
app.module.ts:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms’;
---------------------------
Template Driven Forms
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
Model Driven Forms or
Reactive Forms
• In reactive forms, you can control the form completely from the component
class and hence you will get direct, explicit access to the underlying forms
object model.
• Hence, reactive forms are also known as 'model-driven forms'. As reactive
forms are more robust and scalable, they are more suitable for creating all kind
of forms in an application, irrespective of the size of form.
app.module.ts:
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms’;
--------------------
import { RegistrationFormComponent } from
'./registration-form/registration-form.component';
imports: [
BrowserModule,
ReactiveFormsModule
],
----------------------
})export class AppModule { }
Model Driven Forms or
Reactive Forms
Command:ng generate component RegistrationForm
Install Bootstrap:
Command: npm install bootstrap@3.3.7 --save
registration-form.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from
'@angular/forms’;
------------------------
export class RegistrationFormComponent implements
OnInit {
registerForm!: FormGroup;
submitted!:boolean;
Model Driven Forms or
Reactive Forms
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
address: this.formBuilder.group({
street: [],
zip: [],
city: []
})
});
}
}
registration-form.component.html:
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
Model Driven Forms or
Reactive Forms
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control"
formControlName="firstName">
----------------------------------------
<label>Last Name</label>
<input type="text" class="form-control"
formControlName="lastName">
----------------------
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control"
formControlName="street">
<label>Zip</label>
Model Driven Forms or
Reactive Forms
<input type="text" class="form-control"
formControlName="zip">
<label>City</label>
<input type="text" class="form-control"
formControlName="city">
</fieldset>
</div>
<button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{
registerForm.get('firstName')?.value }} </p>