#21 How does an Angular Application Work?
Every Angular app consists of a file named angular.json
. This file contain all the configurations of the app. While building the app, the builder looks at this file to find the entry point of the application. Following is an example of angular.json
file:
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-starter",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/style.css"
]
}
}
Inside the build section, the main property of the options object defines the entry point of the application which in this case is main.ts
.
The main.ts
file creates a browser environment for the application to run, and, along with this, it also calls a function called bootstrapModule
, which bootstraps the application. These two steps are performed in the following order inside the main.ts
file:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
The line above bootstraps the AppModule
.
The AppModule
is declared in the app.module.ts
file. This module contains declarations of all the components.
Below is an example of app.module.ts
file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }
As one can see in the above file, AppComponent
is getting bootstrapped.
This component is defined in app.component.ts
file. This file interacts with the webpage and serves data to it.
Below is an example of app.component.ts
file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}
Each component is declared with three properties:
- Selector - Used for accessing the component
- Template/TemplateURL - Contains HTML of the component
- StyleURL - contains component-specific stylesheets
After this, Angular calls the index.html
file. This file consequently calls the root component that is app-root
. The root component is defined in app.component.ts
. This is how the index.html
file looks like:
<!doctype html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Angular</title>
<base href="/">
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
The HTML template of the root component is displayed inside the <app-root>
tags.
#22 What is the purpose of innerHTML in angular?
The innerHTML
property is used to set or get the HTML content of an element dynamically. It allows you to manipulate the HTML content of an element directly from the component class.
Let's display the below html code snippet in a <div>
tag as below using innerHTML binding:
<div [innerHTML]="htmlSnippet"></div>
and define the htmlSnippet property from any component
export class myComponent {
htmlSnippet: string = '<b>Hello World</b>, Angular';
}
Unfortunately this property could cause Cross Site Scripting (XSS) scripting bugs when improperly handled.
#23 What is the difference between interpolated content and innnerHTML?
The main difference between interpolated and innerHTML code is the behavior of code interpreted. Interpolated content is always escaped i.e, HTML isn't interpreted and the browser displays angle brackets in the element's text content. Where as in innerHTML binding, the content is interpreted i.e, the browser will convert < and > characters as HTMLEntities. For example, the usage in template would be as below,
<p>Interpolated value:</p>
<div >{{htmlSnippet}}</div>
<p>Binding of innerHTML:</p>
<div [innerHTML]="htmlSnippet"></div>
and the property defined in a component.
export class InnerHtmlBindingComponent {
htmlSnippet = 'Template <script>alert("XSS Attack")</script> <b>Code attached</b>';
}
Even though innerHTML binding create a chance of XSS attack, Angular recognizes the value as unsafe and automatically sanitizes it.
#24 What is view encapsulation in Angular?
In Angular, view encapsulation is a mechanism that encapsulates the styles defined in a component's stylesheets to prevent them from affecting other parts of the application. It ensures that styles defined within a component are scoped to that component's template and do not leak into other components or the global styles.
Angular provides three view encapsulation options:
- Emulated (default):
- In the emulated view encapsulation mode, Angular emulates the shadow DOM behavior by adding a unique attribute to each element in the component's template. This attribute serves as a namespace for the component's styles, ensuring that they only apply to the elements within the component.
- Emulated encapsulation ensures that styles defined in a component do not leak into other components or the global styles, providing component isolation without requiring browser support for native shadow DOM.
- Shadow DOM (deprecated):
- Shadow DOM view encapsulation uses the browser's native shadow DOM implementation to encapsulate styles. It creates a shadow DOM subtree for each component and applies the component's styles to that subtree, ensuring that they do not affect other parts of the application.
- Shadow DOM encapsulation provides true component isolation by using the browser's built-in encapsulation mechanism. However, it requires browser support for native shadow DOM, which is not universally available across all browsers.
Note: Shadow DOM encapsulation is deprecated in Angular and will be removed in future versions.
- None:
- In the none view encapsulation mode, Angular does not apply any encapsulation to the component's styles. Styles defined in the component's stylesheets will be applied globally, affecting the entire application.
- None encapsulation mode should be used with caution, as it can lead to style conflicts and unintended side effects when multiple components define conflicting styles.
- This mode is typically used for special cases where you intentionally want to share styles across multiple components or apply global styles to the entire application.
You can specify the view encapsulation mode for a component by setting the encapsulation property in the @Component decorator:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
encapsulation: ViewEncapsulation.Emulated // or ViewEncapsulation.ShadowDom or ViewEncapsulation.None
})
export class ExampleComponent {
// Component logic here
}
Overall, view encapsulation in Angular helps ensure component isolation and maintainability by scoping styles to individual components, thus reducing the risk of style conflicts and improving the maintainability of Angular applications.
#25 Difference between Local Storage and Session Storage?
Feature | localStorage | sessionStorage |
---|---|---|
Lifespan | Persists even after browser is closed | Cleared when browser session ends (tab closed) |
Scope | Origin-based | Origin-based |
Storage Limit | Varies by browser; typically larger than cookies | Varies by browser; typically larger than cookies |
Data Access | Accessible via localStorage object | Accessible via sessionStorage object |
Usage | Storing long-term data (e.g., user preferences) | Storing temporary data (e.g., session-specific information) |
- Lifespan:
- localStorage: Data stored in localStorage persists even after the browser is closed and reopened. It remains available until explicitly removed by the user or cleared by the application.
- sessionStorage: Data stored in sessionStorage persists only for the duration of the browser session. Once the browser tab or window is closed, the data is cleared and no longer available.
- Scope:
- Both localStorage and sessionStorage are scoped to the origin (i.e., the combination of protocol, host, and port) from which they were accessed. Data stored in one origin cannot be accessed by pages from a different origin due to the Same Origin Policy enforced by browsers.
- Storage Limit:
- The amount of data that can be stored in localStorage and sessionStorage varies between browsers, but both typically have a larger storage limit compared to cookies.
- The exact storage limit depends on the browser and may range from a few megabytes to several megabytes per origin.
- Data Access:
- Data stored in localStorage and sessionStorage is accessible via JavaScript using the localStorage and sessionStorage objects, respectively.
- Data is stored as key-value pairs and can be retrieved, updated, or removed using methods such as getItem(), setItem(), removeItem(), and clear().
- Usage:
- localStorage is commonly used for storing user preferences, settings, or other long-term data that needs to persist across browser sessions.
- sessionStorage is often used for storing temporary data or session-specific information that is only needed for the duration of a browser session.
Example:
// Storing data in localStorage
localStorage.setItem('username', 'John');
localStorage.setItem('isLoggedIn', 'true');
// Retrieving data from localStorage
const username = localStorage.getItem('username');
const isLoggedIn = localStorage.getItem('isLoggedIn');
console.log('Username:', username); // Output: Username: John
console.log('IsLoggedIn:', isLoggedIn); // Output: IsLoggedIn: true
// Storing data in sessionStorage
sessionStorage.setItem('token', 'abc123');
sessionStorage.setItem('isAdmin', 'false');
// Retrieving data from sessionStorage
const token = sessionStorage.getItem('token');
const isAdmin = sessionStorage.getItem('isAdmin');
console.log('Token:', token); // Output: Token: abc123
console.log('IsAdmin:', isAdmin); // Output: IsAdmin: false
#26 What are different types of compilers used in Angular?
In Angular, we use two different kinds of compilers:
- Just-in-time (JIT) compiler
- Ahead-of-time (AOT) compiler
These two compilers are useful, but they serve very different purposes. Our browser can't understand TypeScript. It can understand only JavaScript, so a JIT compiler compiles TypeScript to JavaScript.
The compilation is performed in the development environment. If it takes less time to compile and more time to develop for stepping through functions quickly. The JIT compiler is used when you deploy your app locally using the ng serve or ng build commands or create an uncompressed build of your entire code base.
On the other hand, AOT compilers are used to generate lightweight production builds of the entire code base, ready to use in production. To use the AOT compiler, the ng build command should be used with the –prod blog.ng build –prod.
This tells the Angular CLI to create an optimized prod build of your codebase. It will take some time as it does some optimizations, such as: Shrinking can take some time, but you can save that time for production builds.