0% found this document useful (0 votes)
2 views

Angular_(AutoRecovered)[1]

The document provides an overview of Angular, a JavaScript framework for building single-page applications, explaining the differences between frameworks and libraries, and detailing the necessary steps to set up an Angular environment. It covers Angular's data binding techniques, directives, component communication, and lifecycle hooks, emphasizing the importance of component separation for maintainability. Additionally, it discusses Angular's version history and the installation process for required tools like Node.js and Angular CLI.

Uploaded by

khaled1.alqemam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Angular_(AutoRecovered)[1]

The document provides an overview of Angular, a JavaScript framework for building single-page applications, explaining the differences between frameworks and libraries, and detailing the necessary steps to set up an Angular environment. It covers Angular's data binding techniques, directives, component communication, and lifecycle hooks, emphasizing the importance of component separation for maintainability. Additionally, it discusses Angular's version history and the installation process for required tools like Node.js and Angular CLI.

Uploaded by

khaled1.alqemam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Angular:

Part One:
What is angular?

Angular is a js framework which allows you to build and create single page applications
what is the difference between framework and library?

 You need to ask yourself who calls whom?

In the framework scenario

The framework calls your client code and execute it

In the library

Client code call the library code (like the jQuery)

 In framework you have structured constraint you in library there is no structure you follow or
must to follow

‫ ف حالة ال‬execute ‫ للكود بتاعك ويعمل له‬call ‫ هو اللي بيعمل‬framework ‫يبقي اول حاجة ال‬
library ‫ الكود الخاص بال‬execute ‫ و ي‬call ‫ الكود بتاعي هو اللي بيعمل‬library
‫ معنديش‬library ‫ معين ملتزم بي ف حالة ال‬structure ‫ انا ملتزم ب‬framework ‫ف حالة ال‬
‫الكالم ده‬

What is the single page application?

In the single page application, you only have a single page and never changed when routing or others
actions
but what happened the html code and js code of the page is changed at runtime for the same page
one page and when navigation it is html and js and css changed at runtime
you can navigate from page to page without reload
__________________________

Angular versions?

Angular at the beginning it is called angular js

Angular js is very different about angular and it is the first version

Angular 2  it is the first start by typescript

__________________________

What I need to start with angular?

1 – install node js (need to have the node package manager to install angular cli) node js installed
automatically with the node package manager (LTS Version Lon<g Time Support Version)

2 – install npm node package manager


3 – install angular cli (with this create component create project )

4 – Text editor

How to know the version of node js downloaded on your device?

Node -v

How to install more than one version of the node js on your device?

Install nvm  node version manager

And after this say nvm install 13 --? It is version you want to install

Nvm use 20  it is the version you use

How to know the version of the node package manager ?

Npm -v

How to install the angular CLI by npm?

Npm install -g @angular/cli

Anything you want to do with the angular cli start with ng

How to know the version of the angular installed on your device?

Ng version

The version of the application created as the version of your current angular cli

How to create you first angular app?

Ng new name –standalone false

How to run your angular app?

Go to the source folder path in the terminal and then ng serve

Angular application by default run on port 4200

Why say by default  it is mean it can be changed

To change the port

Ng serve –port 4321  give it the port you need to run on

When you write in the terminal ng serve what happen in the background?

This command calls a file called main.ts

And this file makes something called bootstrap module for appmodule
Meaning it is calling a module called AppModule and this is the entry point for my app

And the appmodule call or bootstrap for the appcomponent which is the entry point or root component
for my module

Any component in angular when creating in angular created with four files:

1 – one for the html code

2 – one for the style

3 – one for testing

4 – one for the logic

Before the standalone any application you create it is create with one module and what we called it root
module

And also one component called app component

Where is the single page application that we talking about index.html

What the module?

It is a type script class

Anything start with @ prefix in angular it is a decorator

Decorator is about attach additional information to the class related to it

@Ngmodule  it is making the class related to it as a module and give it a feature related to the module

What the features it can take


1 – declarations array  the component names inside or related to this module

2 – imports array  the module can use another modules inside it so it is added to it

3 – Providers array  inject the service inside it

4- bootstrap array  contain the entry point for the module

@Component  it is making a class related to it as a component

1 – selector  is the name used to the call this component like alias name

2 – templateUrl  the html file path

3 – styleUrl  the style path related to it

Decorator  it is a pattern add additional information to the class related to it

The component can have multiple styles pages

So make it StyleUrls and it is take array []


How to install bootstrap in you application?

Npm install --save bootstrap

--save  to put it in the dependencies

Now you install the bootstrap but you don’t ready to use it ready you must go to the angular json

Go to the styles array which contain the shared styles in your app put it the path of your bootstrap

Package.json  to know the packages installed your app go to the dependencies in the package.json file

The scripts in it when you say

Ng serve it is called npm start

Ng build it is called npm build

And so on

Angular.json  contains the configurations related to your angular project

How to split our home page that inside the app component?

Header + footer + main

So we need a Header component

Main Component

Footer Component

And the wrapper for all is the App Component

How to create a component?

Ng g c Name

G  for generate

C  for component
Part Two:
Angular binding :
Is the way data connects between the typescript and the html
One way binding:
1 – interpolation: used to display data in the template (works with variables,
expressions, and method calls)
2 – Property Binding: used to set element properties dynamically (src, disabled,
value)
3 – Event Binding used to handle user interactions (clicks, keypresses, input
changes)
Two way Binding:
Used for form elements(input, textarea, select) Requires FormsModule in
app.module.ts

What is the binding?

You have two files’ data transferred between them html file and typescript file of your component,

Sometimes you will have data from js to your html or from the typescript to your html page

This is the binding

If you have data in html and want to move it to typescript or the opposite

If you have the data in the type script and want to send to html it is called the data binding

And if you have some element in html and it will execute some action in the typescript it is event binding

And this two called one way binding (data binding (from typescript to html ) or event binding (from html
to typescript)

And sometimes you need the both binding and this called (two binding (it is the combination of data
binding and event binding)

Data Binding Have Several types:

1 – Interpolation
2 – Property Binding

3 – Style Binding

4 – class binding

Interpolation (string interpolation):

{{property or field value or method execution result}}

This above format called string interpolation

Property Binding:

[disabled]=’!allowedAddServer’

What is the difference between the interpolation and property binding?

String interpolation work the values as string

But in the case of the property binding it is work with the datatypes itself so if it changed it will know the
changes

Event Binding:

To Bind On Event

(click) and assign to it the event handler

Two way data binding:

You need first to work with the two way data binding to import a module called FormsModule in your
imports module

The two binding is to execute the event and data binding together

[]  this is for data binding ()  this is for event binding

[()] the two together for two way binding

[(ngModel)] =”Property”

It is about simulate the two way binding

What is the directives in angular?

Directives is instruction to the dom (some actions done of the dom)

Directives is a group of classes that can add behavior or modify behavior of an element

The first directive

Ng if structure directive  it is responsible to hide some element depend on some condition


Structure directive start always with asterisk * <p *ngif=”Property”> so this paragraph will appear if the
property is true else will not appear

If I want to create if else

To make something hidden in the start and appear depend on some condition use ngTemplate directive

<ng-template> </ng-template>

But how to make the two element related to each other you need to take the element in your hand or
select it so we use what called in angular template reference variable (it is used to refer some element in
html)

How to put it go to the element #name

<p *ngif=”property;else refernceName>

But this before angular 16 after this


@if(Property){}

@Else{}

Style Binding:

We bind on some object to bind using style binding you use a directive called [ngStyle] and pass to it the
object you want to bind to it

Style binding in Angular allows you to set the inline styles of an element dynamically. It provides a way to
bind an element's style properties to component properties or expressions.

[style.property]="expression"

Purpose: Used for binding a single CSS style property to an expression (usually a string or a variable).

Usage: Typically used when you need to bind only one style property at a time.

<div [style.background-color]="bgColor">

This div has a dynamic background color!

</div>

<div [ngStyle]="divStyles">

This div has dynamic styles!

</div>

[ngStyle] (ngStyle Directive):


 Purpose: Used for binding multiple CSS properties at once by passing an object where each key
is a CSS property, and the value is the corresponding style.

 Syntax: You use [ngStyle] to bind to an object or a map of CSS properties.

 Usage: Useful when you need to set multiple styles dynamically.

Class Binding:

Class Binding in Angular allows you to dynamically add or remove CSS classes from an HTML element
based on an expression. It’s similar to style binding, but it works with CSS classes rather than inline style

<div [class.highlight]="isHighlighted">

This div has dynamic class binding!

</div>

<button (click)="toggleHighlight()">Toggle Highlight</button>

In this you bind to a set of classes depend on some conditions

You have a set of css class and need to bind it depend on some condition you use a directive called
[ngClass] and pass to it your object

Ngfor directive

Before angular 16

<p *ngFor="let server of Servers">


{{server}}
</p>

After angular 16

@for  come to make the syntax more better and more perfomrmant

But it must have a track expression

Required and used to optimize the performance to not retender the whole array if the data changed

For loop must have a track expression

Required for optimize the performance to no rerender the whole data if change occurred

At the old if data changed it is rerender the whole array if any change occurred on it

With track it is track the data if no change occurred on in it let them as they are and change only the
changed part

By this we enhance a performance very better


The tracked value is used to compare if changes occurred and must be unique value

@for (item of Servers; track item)


{
{{item}}
}

Part Three:

We need to split the application as much as to component “separation of concern “ for better
maintainability and scalability

To not make initialize to all elements in typescript and CompilerOptions  strictPropertyInitialization 


false

How to pass the data from the parent component to the child component?

Who say or how determine which is the parent and which is the child

It is depend on where the selector used if the selector of some component used in another component
so this component is child for the component used in

So how now to send data from parent to child component

Use decorator called input decorator


input decorator  to send data from parent component to child component

Go to the selector of the child in the parent component and use the property in the child that will
contain the data [childProperty] = “parentProperty”

But you need to make the property in the child and make it in the type script @Input()

When you say this this mean the property will be send from the parent

You can give it a special name from you can make the property in the child what you want

And in the child @input(“your special name”)

What if you want to send data from child to parent component?

you can pass data from a child component to a parent component using the @Output decorator and the
EventEmitter

To pass data from child component to parent component use the output decorator with event emitter

The data sended from the child is $event also

Make some event in the parent that will take the data exposed from the child that take the $event data
And handle what you want to make from the child sended data

On the selector of the child make some event that will fire your event and assign your parent event to it

Define as you want event according to the data sended from the parent to child each one has it is own
event

So the child must have event also as what to send from the child to parent

Always the child data want to send event must be from type EventEmitter<>();

In the child event must send the data to the parent

Use the event you define and make to it emit(data)

You must mark it as output decorators

From parent to child  input decorator

From child to parent  output decorator

Always be from the child perspective  if it will the data so input decorator

If the data will out from it output decorator

How to make the input property required to make the input property must be required

@Input({required:true})

In the case if no data exists in the collection use the @empty to view what you want

You can define what you need by $index ,$count, $first , $last, $even ,$odd

In the structure directive there is a switch

@switch(value){

@case(targetValue)

@default{

Part four

is a decorator in Angular that allows you to get a reference to a child component, directive, or DOM
element within a parent component. It is commonly used when you need to interact with a child
component programmatically (e.g., calling a method or accessing a property)child elements and their
properties or methods directly from the parent component class.
@ViewChild is only available after the view initializes, so you should use it inside ngAfterViewInit().

ViewChild does not work in ngOnInit() because the view is not yet initialized.

1. If you need @ViewChild to work in ngOnInit(), use { static: true }.

If you need to update the child component dynamically, use the { static: false } option (default).

View Child help you to access the child component you have in the parent component

If you have a parent and want to access the child component from it

Go to the parent component and use @ViewChild(Typeofchild) card:TypeofChild;

By this you say you want to access the child component

You can print this component by this you have the access to child component from the parent
component from the parent

It is a decorator help to access the child element

If I have multiple selectors and use the view child it return the first

From the view child you can access the first one only the first element

Template reference value #cardRef

In the parent component you can access the child by the template reference @ViewChild(‘cardRef’)
card:TypeOfChild

There is no deference between two until now

When you have access to child component you can access all public properties and methods inside it

By the template reference variable, you can access any one you want

In the output decorator you send data one by one and in the view child you have access all the public
properties and methods you want

If you want to select multiple children make a container around it and give it a template reference
variable

And define a view child from the type ElementRef

But if you have a wrapper around also multichildren you also can access only the first child

You can define the child to element ref to be native element inside it to access what you want from the
native element

@(“cardRef’,{read:ElementRef} card:ElementRef;

The benefit of the element ref is to work with the element as an ordinal html element work with the
child as Html Element without any problem
If you want to access the view child you must wait until the view rendered in dom and than access the
view child

So If you try to log the view child it will give you undefined

You cannot access the view child in the constructor because in the constructor the my component and
it is children not loaded or rendered in the dom

In this case we use lifecycle method in our component any component in angular have it is life cycle

So you must access the AfterViewInit

You must implement the AfterViewInit or make it static true and you can access it else will give you
undefined
export class MainComponent implements AfterViewInit , OnInit {

courses:Array<Course> = courses;

@ViewChild('loop',{read:ElementRef ,static:true}) addCourseComponent: ElementRef;

ngAfterViewInit() {

console.log(this.addCourseComponent);}

ngOnInit()

console.log(this.addCourseComponent);

This will give you a method called ngAfterViewInit

If you try to access it or log it it will give you the value not undefined

So the viewChild cannot accessed in the constructor of the component because the html related to it not
rendered or loaded on the constructor yet

We have another decorator called viewChildren

It is work as view child but instead but you can query multiple children or collection of the childrens you
have

@viewChildren(ChildType) cards: QueryList<ChildType>;_

You can access it as ElementRef

@viewChildren(ChildType, {read:EllementRef}) elements:quertList<ElementRef>()

Content Projection
Is a pattern that allows you to insert content dynamically into a component view from a parent
component

It enables you to create reusable components where content can be project into the component
template

Key concepts

Ng-content directive is used to define the spot in the child component template where the content
from the parent component will be inserted

Single slot projections this is the simplest form of content projection where you project content into
single spot in the child component template

Multi slot projection this allows you to define mulitpple places in the child component template to
project different content from the parent

What and what is the benefit of content projection?

You can alias in the template page

*ngif = ‘Courses[0]as course’

And then use it in the template page

What Is the meaning of content projection?

I have some content and need to access it from a another place

If I have a child component and used in parent component and put inside the inside the selector and put
image tag

Inside the selector

How to make the child can access this data or the data between the selector tag

You can go to anywhere in the child component template page

The child can display the data send from the parent to the child in the selector by the ng-content
selector

Content Projection : I project content come from parent or display content come from parent

But if you have multitages sended and need to display a part from the content not all you can use the

Which tage want to display with ng-content select=”img”

The parent send some content and I display this content with the ngcontent selector

If you want from the child to access the content parent send in the selector

You can make a template reference variable and through view child in the child component access it

Not view child but Content Child


If the parent send you a content and you want to access this content must assign to if first reference
variable and from the child component access it with the Content Child

What is the difference between view child and content child

The view child is used to access the data of the child component used in the parent from the parent
component

The content child is used to access the data send from the parent to child to access this data in the child

But used to access html any other way access the typescript

In Angular, both @ContentChild and @ViewChild are used to query and access elements or directives in
your templates, but they serve different purposes and work in distinct contexts. Here’s a breakdown of
the differences between them:

1. @ViewChild

 Purpose: @ViewChild is used to access elements or components that are part of the current
component’s view.

 Scope: It only works with elements or child components declared within the component’s
template (i.e., inside the component's templateUrl or inline template

@ContentChild

 Purpose: @ContentChild is used to access content projected into the component via ng-
content. It allows you to access DOM elements or components that are passed from the parent
component into the child component (using content projection).

 Scope: It works with elements, directives, or components that are passed as content from the
parent component to the child component’s template, via ng-content.

 Key Differences:

Feature @ViewChild @ContentChild


Accesses elements inside the Accesses projected content passed from the
Purpose
component’s template (view) parent component
Works with elements in the Works with projected content in the
Scope
component’s own view component’s template
When you are dealing with content
When you need to interact with child
Use Case components or elements inside the projection (ng-content) and need to access
same template the projected content
Where to When you use <ng-content> to project
Inside the component's own template
Use content into the component
Available after content has been projected
Timing of Available after the view has been
into the component (after content
Access initialized
initialization)
Static flag Supports `static: true false`
Feature @ViewChild @ContentChild
support

You can pass the component to another component in the content also as same as any html elements
the same approach

And by this approach you can use the ContentChild with the component type instead of the template
reference variable

Content child is as view child access the first element only

You have ContentChildren to access all the children from this type and it is type from the query list

You can access the content child or children on the ngAfterViewInit but the better approach to access in
the ngAfterContentInit

And you can pass the second parameter object to work with them as ElementRef  {read:ElementRef}

Custom Directive

Directives in Angular are classes that allow you to manipulate the DOM (Document Object Model) by
adding behavior to elements or components. Directives are a fundamental part of Angular, allowing
you to extend HTML functionality in a declarative way. They can be used to add dynamic behavior to
elements, change their appearance, or modify their behavior.

Structural Directives:

 These directives are used to modify the DOM layout by adding, removing, or manipulating
elements.

 Structural directives change the structure of the DOM by adding or removing elements based
on certain conditions.

Attribute Directives:

 These directives modify the behavior or appearance of an element, component, or another


directive.

 Attribute directives change the appearance or behavior of an element (e.g., adding a class,
changing styles, handling events).

 Common examples of attribute directives are:

o ngClass: Adds or removes CSS classes to an element.

o ngStyle: Adds or removes inline styles to an element.

o ngModel: Binds the value of an input element to a variable.

Component Directives:
 These are essentially components in Angular. A component is a special kind of directive with a
template.

 A component is also considered a directive, but it comes with its own template and view.

What are Custom Directives in Angular?

Custom directives are user-defined directives that allow you to create specific behavior or
DOM manipulations that Angular doesn’t provide out-of-the-box. With custom directives, you
can encapsulate common behavior and reuse it across multiple components or applications.

You can create custom directives for both structural and attribute purposes.

How to Create a Custom Directive in Angular

1. Custom Attribute Directive

2. You can create a custom directive that modifies the behavior or appearance of an
element.

ng generate directive hoverBackground

In Angular, @HostListener is a decorator that allows you to listen to events on the host
element of the directive or component. The host element is the element to which the directive
or component is attached.

The @HostListener is typically used to respond to DOM events (like mouse events, keyboard
events, etc.) on the host element and call a method in the component or directive when that
event occurs.

@HostListener(eventName: string, args?: any[])

 eventName: The name of the event you want to listen for (e.g., click, mouseenter, keydown,
etc.).

 args: An optional array of arguments to be passed to the method when the event is
triggered.

. ElementRef and Renderer2 Purpose

 ElementRef: This provides a reference to the native DOM element, but you should not
manipulate the DOM directly in Angular. Directly using ElementRef to access the DOM is
discouraged because it bypasses Angular's rendering system, which can lead to issues such as
breaking the Angular change detection or inconsistent views when the DOM updates.

 Renderer2: This is the recommended way to interact with the DOM in Angular. It's an
abstraction over direct DOM manipulation, and it helps ensure that the code works across
different platforms (like server-side rendering) while also ensuring security against XSS (Cross-
Site Scripting) vulnerabilitie
In Angular, ElementRef and Renderer2 are both used to interact with DOM elements, but they
serve different purposes and should be used in different scenarios. Here's the difference
between the two:

1. ElementRef:

 Purpose: It provides direct access to the underlying DOM element.

 How it's used: ElementRef is typically used to interact with an element directly within the
component, such as accessing its properties or manipulating it.

 Access: When you use ElementRef, you directly access the native DOM element through the
nativeElement property.

Potential Issues: Directly manipulating the DOM with ElementRef bypasses Angular's change
detection and security mechanisms, which may lead to issues like:

 Bypassing security: For example, Angular uses Renderer2 for sanitizing operations to prevent
XSS (Cross-Site Scripting) attacks.

 Not platform-agnostic: ElementRef is tied directly to the DOM, which means it might not work
on other platforms like Web Workers or mobile apps using Angular Universal or Ionic.

Renderer2:

 Purpose: It is used for safely interacting with the DOM. It provides an abstraction layer that
allows for manipulation of DOM elements in a way that is platform-agnostic and does not
directly access the native DOM. This is crucial for making the application more secure,
modular, and compatible across different platforms.

 How it's used: Renderer2 should be preferred when you need to manipulate the DOM, as it
provides methods for tasks like adding/removing classes, setting styles, setting attributes,
appending/creating child elements, etc.

Advantages:

 Platform Independence: Renderer2 works in environments other than the DOM, such as Web
Workers or mobile environments (like Ionic or Angular Universal).

 Security: When you manipulate the DOM using Renderer2, Angular can ensure proper
sanitization of the content and prevent XSS vulnerabilities.

 Abstraction: It abstracts away direct DOM manipulation, allowing Angular to handle platform-
specific implementations and optimizations.

Summary of Differences:

Feature ElementRef Renderer2

Direct access to the native Abstraction for manipulating the


Purpose
DOM element. DOM safely and securely.
Feature ElementRef Renderer2

Methods to manipulate the


Direct access to
Access Type DOM (e.g., addClass(),
nativeElement.
setStyle()).

Platform Tied directly to the DOM Works across platforms (DOM,


Independence (not platform-agnostic). Web Workers, etc.).

No built-in security
Provides security features like
Security features (e.g., XSS
DOM sanitization.
protection).

When DOM manipulation is


When direct access to the
When to Use needed in a platform-agnostic
DOM element is required.
and secure way.

When to Use Each:

 Use ElementRef when you absolutely need to access or manipulate the DOM element directly,
but it’s recommended to limit this usage due to security and maintainability concerns.

 Use Renderer2 for all DOM manipulation in Angular, especially when you need a platform-
agnostic solution, as it is more flexible, secure, and integrated into Angular's ecosystem.

Summary of Differences:

Feature ElementRef Renderer2

Direct access to the native Abstraction for manipulating the


Purpose
DOM element. DOM safely and securely.

Methods to manipulate the


Direct access to
Access Type DOM (e.g., addClass(),
nativeElement.
setStyle()).

Platform Tied directly to the DOM Works across platforms (DOM,


Independence (not platform-agnostic). Web Workers, etc.).

No built-in security
Provides security features like
Security features (e.g., XSS
DOM sanitization.
protection).

When DOM manipulation is


When direct access to the
When to Use needed in a platform-agnostic
DOM element is required.
and secure way.

When to Use Each:


 Use ElementRef when you absolutely need to access or manipulate the DOM element directly,
but it’s recommended to limit this usage due to security and maintainability concerns.

 Use Renderer2 for all DOM manipulation in Angular, especially when you need a platform-
agnostic solution, as it is more flexible, secure, and integrated into Angular's ecosystem.

Great question! If you're using Renderer2, you typically don't need to inject ElementRef unless
you need to directly access the native DOM element in your component or directive. Here's
why

1. Why Renderer2 is usually sufficient:

Renderer2 is the Angular abstraction layer for DOM manipulation. It provides methods to safely
manipulate elements (such as adding/removing classes, changing styles, etc.), and it's platform-
agnostic, which means it works not only in the browser but also in environments like server-side
rendering or mobile platforms.

Since Renderer2 can perform most of the DOM manipulations you need (like setStyle(),
addClass(), removeChild(), etc.), you don't need ElementRef in most cases. Renderer2 is the
preferred way to modify the DOM in Angular, as it ensures your code is platform-independent
and safe.

2. Why you might still inject ElementRef:

However, there are cases where you might still want to inject ElementRef:

 Access to nativeElement: If you need direct access to the native DOM element (for example, to
get its dimensions, position, or interact with its native properties), ElementRef provides access to
the nativeElement property, which gives you direct access to the DOM element. Renderer2
doesn’t provide direct access to the native DOM element.

 Special DOM properties: There might be certain properties or methods that you can only access
directly via the native DOM, and Renderer2 doesn't provide methods for those specific
properties. For example, certain events or attributes might require direct access to the
nativeElement.

 Non-DOM manipulations: Some scenarios might involve Angular's change detection or lifecycle
hooks, where you may need to reference the element itself in a more fine-grained manner that
Renderer2 can't handle (e.g., working with a native form control directly)

 When to Avoid ElementRef:


 In general, if you're only doing DOM manipulations (e.g., adding/removing styles,
changing attributes), you should prefer Renderer2 over ElementRef. Accessing
nativeElement directly can lead to tight coupling between your code and the browser's
DOM, and it may cause issues in other environments like server-side rendering or web
workers.
In Angular, a structural directive is a type of directive that is responsible for adding or removing
elements from the DOM based on some condition. They are used to change the structure of the
DOM by adding, removing, or manipulating DOM elements.

To create a custom structural directive, you typically use the TemplateRef and ViewContainerRef
classes from Angular.

Difference Between TemplateRef, ViewContainerRef, ElementRef, and Renderer2 in Angular

Each of these Angular classes serves a different purpose when working with the DOM

1. TemplateRef

📌 What is it?
TemplateRef represents an embedded Angular template (ng-template). It provides access to
the content of a template that hasn't been inserted into the DOM yet. You use it to create and
render dynamic content programmatically.

📌 Use case:

 Used in structural directives like *ngIf, *ngFor, and custom directives to dynamically insert
templates.

 Works with ViewContainerRef to create views

📌 Key Points: ✔ TemplateRef holds a blueprint (not yet attached to the DOM).
✔ It is typically used inside directives to access ng-template content.
✔ Alone, it does nothing—it needs ViewContainerRef to instantiate its content.

2. ViewContainerRef

📌 What is it?
ViewContainerRef is a container that holds dynamic views. It is used to dynamically add or
remove views from the DOM.

📌 Use case:

 Works with TemplateRef to render templates dynamically.

 Used for dynamic component creation (e.g., using ComponentFactoryResolver).

 Used in structural directives like *ngIf, *ngFor.

📌 Key Points: ✔ ViewContainerRef manages the lifecycle of embedded views.


✔ Can be used to dynamically insert, remove, and manipulate templates and components.
✔ Works with TemplateRef to create embedded views.

How to write your own custom attribute directive and how to work with?

This is attribute directive not structure directive

Directive folder
To create directiv3e

Ng generate directive NameOfDirective “BasicHiehLight”

Directive it only a class have a decorated called @directive decorator

And the user use the directive with the selector name

Use case

When use this directive with any element make it is background color to be gray

Any directive when working with it have a ref from the element so you can accept within the constructor

Accept it as ElementRef

Native element you get the current element

nativeElement.style.backgroundColor =””

another way to make the same

with a render to accepted in constructor also

a type from Render2

render.setStyle(this.element.nativeElement, “property”,”value”)

this is not the best way to change the style because you sometimes need to recall another element in
another place and the style will be changed in this other element

use case if I want to listen on a specific event like the hover and in hover in and out change the color

when you use the custom directive to listen on a specific event you must use what know as host listener
decorator

how to use the host listener decorator

in mouse enter

@HostListener(“event”) mouseover(EventData:Event){

In mouse out

@HostLisnent(“mouseLeave”) mouseLeave(EventData:Data)

{}

Instead of using the rerender to change the style

You have another way using HostBinding decorator

@HostBinding(“style-backgroundColor) backgroundColor:string;
And inside the two decorator for the host listener

Change the hostBinding variable if you want

This.backgroundColor =”value”

If I want to pass a specific data from the element using the directive to a specific color

Take it as input decorator

@Input() defayktColorLstring

And pass it to the element that using the directive

Directive [inputProperty] = value

When the directive is called

Log in it is constructor it is created after the component rendered

Make a class in css called heighlighted

You can hostbinding on this class using

@hostBinding(“className”) get getClasse(){return “className”}

Or you can directly bind on the class and make the method return true

@hostbinding(“class.highlighted”) get get class(){return true;}

You can make a input decorator value accept from the client and when it mousover and mouseleave
event cgange this value

How when event when occurred in directive capture it as output decorator with event emitter and we
can toggle in it

You work with the directive as small component

View Encapsulation

What is View Encapsulation in Angular?

View Encapsulation in Angular controls how styles defined in a component affect the DOM. It ensures
that the styles of a component do not leak into other components and are not affected by external
styles.

🔹 Types of View Encapsulation in Angular

Emulated (Default)

How it works: Angular scopes styles to the component by adding unique attributes to
elements.

encapsulation: ViewEncapsulation.Emulated, // Default behavior


The _ngcontent-xyz ensures the styles apply only inside this component.

✅ Pros: Styles are scoped automatically.

🔹 How Does Angular Ensure Styles Apply Only to a Component?

Angular scopes component styles using attribute selectors when ViewEncapsulation.Emulated is


enabled (which is the default).

🔸 How It Works:

 When Angular compiles your component, it adds a unique attribute (e.g., _ngcontent-xyz) to
every element inside it.

 When Angular compiles your component, it adds a unique attribute (e.g., _ngcontent-xyz) to
every element inside it.

When Angular processes your styles, it rewrites them to include the component’s unique
attribute:

p[_ngcontent-xyz] { color: red; }

o This ensures that only elements inside that component get the styles.

Why This Works?

 The attribute _ngcontent-abc only exists inside this component, so other <p> tags outside this
component won't be affected.

 If another component has its own styles, it gets a different attribute, like _ngcontent-xyz.

✅ Ensures encapsulation
✅ Prevents style conflicts across components
✅ No need for manually adding class names

🔹 What If I Use ViewEncapsulation.None?

encapsulation: ViewEncapsulation.None

Angular does not add _ngcontent-xyz.

The styles are global and will affect all <p> elements across the app.

 How it works: Styles are global and apply to the entire application.

Exactly! You're spot on! Here's a quick summary of your understanding:

1. ViewEncapsulation.Emulated (Default)

 Styles are scoped to the current component only.


 Angular adds unique attributes to elements in the component's template, like _ngcontent-xyz.
These attributes ensure that styles are applied only to elements inside that component.

 Other components are not affected by the styles from this component.

2. ViewEncapsulation.None

 Styles become global and will affect all matching elements in the entire application, regardless
of which component they are in.

 Angular does not add any unique identifiers to the styles, so they are not scoped.

 For example, if you define a <p> { color: red; } style in your component, it will apply to every
<p> element in the application.

To Summarize:

 Emulated: Scoped to the component using unique identifiers, styles don't leak.

 None: Global styles that affect the whole application.

Concept or behavior in angular the style of the component is encapsulated inside the component and
not effect outside the application

Each view encapsulate it is css style to not effect the application

If the write style in style.css it is shared on the overall app not only one component

If I put in the component css file will only related to this component

The view now encapsulte it is own style and related to it only

How angular make that because each component take a unique attribute

The default in angular give each component a unique attribute to encapsulation the view

But how it occurred

Take the component selector and give it a some style

But it will not be effect because the style inside the reflect the elements code not the component itself

If I want this reflect to make the host or the component itself take a display itself

So use :host  this mean the component itself need to take a style so it will make the parent element
take this style
The component in this case we called it host

So if you want to give a style to the component itself you don’t use the component itself because the
style itself it is related to the elements inside it or use the :host

If I want to apply a style to an element with a specific class passed to me from the parent with the ng-
content to the child the class will be passed from the parent component

How to make that go to the class that will come from the parent component and say

::ng-deep .parent-class  so if the style will be passed from the parent to the child

The default of the view encapsulation is emulated view encapsulation what it is mean

It is give attribute to each element if this attribute not exist this will be override the child

If you want to stop the eumulated go to the parent component and make the encapsulation to

ViewEncapsulation.None

So the parent style will be applied to the children

If I want to not make the style of the global to not be applied to your component

Use ViewEnapsulation.ShadowDom

Part 6

Component Life Cycle hooks

Component lifecycle hooks are methods that allow you to run custom code at specific points in the
lifecycle of a component or directive these hooks are part of the angular framework and are used to
manage the behavior of components as they are created, updated and destroyed

1- ngOnChanges
and input property of a component changes (@Input())
when any data bound input property changes it receives a SimpleChanges object
containing the previous and current values of the input properties
2 – ngOnInit
The component or directive is initialized
This hooks is called once after the first ngOnChanges call it is used typically for
initialization lofic such as fetching data or setting up intial states
3- ngDoCheck
called when angular runs change detection
this hook is called during every change detection cycle allowing you to
implement custom change detection it gives you a chance to perform actions
when the component state changes
4 – ngAfterContentInit
Called when content (ng-content) has been projected into the component
This hook called once after angular has fully initialized all content projected
into the component it is useful when you need to manipulate or check the
projected content
5 – ngAfterContentChecked
Called when every check of projected content
This hook is called after every change detection cycle in which content is
projected into the component you can use it to react to any changes in the
projected content
6 – ngAfterViewInit
Called when the component view has been fully initialized
The hook is called once after component view including child views has been
initialized it is often used to perform operations that depend on the view such
as interacting with child components or Dom elements
7- ngAfterViewChecked
After every check of the component's view.
This hook is called after every change detection cycle in which component
view has been check it can be used for tasks such as checking dom elements
8 – ngOnDestory
Called when the component or directive is about to destroyed
This hook is called just befor angular destroys the component It is commonly
used for cleanup tasks such as unsubscribing from observables or releasing
resources

Descri Called
Hook
ption When

Input
Input
prope
proper
ngOnChanges rties
ties
chang
change
e

After
ngOnC
hanges
Comp
but
onent
ngOnInit before
initiali
the
zation
view is
initializ
ed

ngDoCheck Custo Every


m change
chang detecti
e on
Descri Called
Hook
ption When

detec
cycle
tion

After
content
Conte has
nt been
ngAfterContentI
projec project
nit
tion is ed into
done the
compo
nent

After
every
change
Conte detecti
ngAfterContent nt is on
Checked check cycle
ed for
project
ed
content

After
compo
Comp nent's
onent view
view and
ngAfterViewInit
is child
initiali views
zed are
initializ
ed

ngAfterViewCh Comp After


ecked onent every
view change
is detecti
check on
ed cycle
for the
compo
Descri Called
Hook
ption When

nent's
view

Comp
Before
onent
Angular
is
destroy
ngOnDestroy about
s the
to be
compo
destro
nent
yed

Any component in angular have a life cycle

Life cycle in angular is a set of methods or functions

You must know every method and when to use it and what is the job of each one

This is the necessary part

The next is the execution path also

1 – ngOnChanges

This function what it is characteristics?

May be executed multiple times not once or one time

When is the first time

It is executed right at the start when the component is created

Whenever one of our input properties changes

When the input property value changes this component is fire

Input decorator

2 – ngOnInit

It is executed once the component has been initialized after the constructor

ngOnInit will run after the constructor not before the constructor

when to use this function like call API and put the values in the properties

3- ngDoCheck

This function run multiple times


Whenever change detection runs

Change detection  it is system used by angular to know if something changed in the view

To update the view

If you want to make some logic when the change detection run

4 - ngAfterContentInit

Whenever the content which is project via ng-content has been initialized

Whenever any ng-content fire content with the content projection run it is run

5 – ngAfterContentChecked

Check the content after initialized in the ngAfterContentInit

Check the content come from parent to do something

Whenever change detection checked the content we are projecting into our component

6 – ngAfterViewInit

Once the view of our component has been finished initializing

So once our view has been rendered in Dom

7 – ngAfterViewChecked

That is called whenever our view has been checked

8 – ngOnDestory

Great place to do some clean up

Unsubscribe to observables

Implements OnInit to take the method ngOnInit

Implements OnChange to implement the method ngOnChange

The constructor will run first after if onChanges after this OnInit

The ngOnChanges take a parameter from type SimpleChange

Contain the element and current value

firstchange and previouseValue

give you the previous and current value of the input property

Services
Services are classes that are responsible for providing specific functionality such as data management
business logic or communication between components services help with separation of concerns and
make it easier to manage complex logic and shared data across different parts of your application

It is allowed you to share a data between different component have a relation between each other or
not

If I want to share data between multiple component  use service

Service is only a class contain some business logic

Service helps you not repeating your code

Folder for services

Ng g s logging

Generate service

The service is a class

It is having a decorator @injectable

Init inside the class is not correct because if this service in the future take some parameter or need some
dependency you will have a problem because you does not use dependency injection

Instead of instantiate inside the constructor you must not coupled to the creation of this

You must inject it inside the constructor

Constructor (private logging:LoggingService)

Part Seven

What is the packages need to start with?

Bootstrap

To use js of boorstrap

Need to add to scripts array in angular.json

when you add script to scripts array need to make a new serve

In angular we use camelCase for variables and for types Pascal Case

To use local assets in asset array the folder must be added

You might also like