Angular_(AutoRecovered)[1]
Angular_(AutoRecovered)[1]
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?
In the library
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 ف حالة ال
الكالم ده
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?
__________________________
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)
4 – Text editor
Node -v
How to install more than one version of the node js on your device?
And after this say nvm install 13 --? It is version you want to install
Npm -v
Ng version
The version of the application created as the version of your current angular cli
When you write in the terminal ng serve what happen in the background?
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:
Before the standalone any application you create it is create with one module and what we called it root
module
@Ngmodule it is making the class related to it as a module and give it a feature related to the module
2 – imports array the module can use another modules inside it so it is added to it
1 – selector is the name used to the call this component like alias name
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
And so on
How to split our home page that inside the app component?
Main Component
Footer 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
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
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)
1 – Interpolation
2 – Property Binding
3 – Style Binding
4 – class binding
Property Binding:
[disabled]=’!allowedAddServer’
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
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
[(ngModel)] =”Property”
Directives is a group of classes that can add behavior or modify behavior of an element
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)
@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">
</div>
<div [ngStyle]="divStyles">
</div>
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">
</div>
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
After angular 16
@for come to make the syntax more better and more perfomrmant
Required and used to optimize the performance to not retender the whole array if the data changed
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
Part Three:
We need to split the application as much as to component “separation of concern “ for better
maintainability and scalability
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
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
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
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<>();
Always be from the child perspective if it will the data so input 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
@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.
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
You can print this component by this you have the access to child component from the parent
component from the parent
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
In the parent component you can access the child by the template reference @ViewChild(‘cardRef’)
card:TypeOfChild
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
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
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;
ngAfterViewInit() {
console.log(this.addCourseComponent);}
ngOnInit()
console.log(this.addCourseComponent);
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
It is work as view child but instead but you can query multiple children or collection of the childrens you
have
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
If I have a child component and used in parent component and put inside the inside the selector and put
image tag
How to make the child can access this data or the data between the selector tag
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
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
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:
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
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:
Attribute directives change the appearance or behavior of an element (e.g., adding a class,
changing styles, handling events).
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.
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.
2. You can create a custom directive that modifies the behavior or appearance of an
element.
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.
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: 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:
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:
No built-in security
Provides security features like
Security features (e.g., XSS
DOM sanitization.
protection).
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:
No built-in security
Provides security features like
Security features (e.g., XSS
DOM sanitization.
protection).
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
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.
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)
To create a custom structural directive, you typically use the TemplateRef and ViewContainerRef
classes from 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.
📌 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:
How to write your own custom attribute directive and how to work with?
Directive folder
To create directiv3e
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
nativeElement.style.backgroundColor =””
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
in mouse enter
@HostListener(“event”) mouseover(EventData:Event){
In mouse out
@HostLisnent(“mouseLeave”) mouseLeave(EventData:Data)
{}
@HostBinding(“style-backgroundColor) backgroundColor:string;
And inside the two decorator for the host listener
This.backgroundColor =”value”
If I want to pass a specific data from the element using the directive to a specific color
@Input() defayktColorLstring
Or you can directly bind on the class and make the method 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
View Encapsulation
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.
Emulated (Default)
How it works: Angular scopes styles to the component by adding unique attributes to
elements.
🔸 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:
o This ensures that only elements inside that component get the styles.
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
encapsulation: ViewEncapsulation.None
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.
1. ViewEncapsulation.Emulated (Default)
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.
Concept or behavior in angular the style of the component is encapsulated inside the component and
not effect outside 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
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 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
If I want to not make the style of the global to not be applied to your component
Use ViewEnapsulation.ShadowDom
Part 6
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
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
nent's
view
Comp
Before
onent
Angular
is
destroy
ngOnDestroy about
s the
to be
compo
destro
nent
yed
You must know every method and when to use it and what is the job of each one
1 – ngOnChanges
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
Change detection it is system used by angular to know if something changed in 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
Whenever change detection checked the content we are projecting into our component
6 – ngAfterViewInit
7 – ngAfterViewChecked
8 – ngOnDestory
Unsubscribe to observables
The constructor will run first after if onChanges after this OnInit
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
Ng g s logging
Generate service
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
Part Seven
Bootstrap
To use js of boorstrap
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