Tuesday 20 April 2021

String Operations

String Operations
To compare an attribute with a string, it is required to surround the string by apostrophes, e.g., where LOCATION = ’HARIDWAR’.

Wild cards (LIKE operator)
 There are two wildcards used in conjunction with the LIKE operator:
 % - The percent sign represents zero, one, or multiple characters
 _ - The underscore represents a single character

For example, if one is interested in all tuples of the table DEPT that contain two C in the name of the department, the condition would be where DNAME like ’%C%C%’.
 The underline stands for exactly one character. Thus the condition where DNAME like ’%C C%’ would require that exactly one character appears between the two Cs.
More string operations are:

upper(<string>) takes a string and converts any letters in it to uppercase,
 e.g., DNAME= upper(DNAME) (The name of a department must consist only of upper case letters.)

lower(<string>) converts any letter to lowercase,

initcap(<string>) converts the initial letter of every word in <string> to uppercase.

length(<string>) returns the length of the string.

substr(<string>, n [, m]) clips out a m character piece of <string>, starting at position n. If m is not specified, the end of the string is assumed.
SELECT SUBSTR('Vertabelo Academy',11,7) FROM DUAL;    -- Academy

CONCAT(first_char, second_char, ... n_char) combines two or more strings into one string
SELECT CONCAT ('Vertabelo Academy is good', ' and great', ' and fantastic!') FROM DUAL;
CONCAT can be replaced by the string concatenation symbol “||”

REPLACE  REPLACE allows you to selectively replace or remove data from inside a string
SELECT REPLACE (‘IRIS Software is good!', 'good', 'great!') FROM DUAL;  -- IRIS Software is great

TRIM  Its main job is removing all specified characters from the beginning part (leading),ending part (trailing), or both parts (both) of a specific string (edit_char).
TRIM( [ [ LEADING | TRAILING | BOTH ] character FROM ] edit_char )
SELECT TRIM(‘    Academy2017    ') FROM DUAL;    -- Academy2017
SELECT TRIM (BOTH '20' FROM '2017VertabeloAcademy20') FROM DUAL;   -- 17VertabeloAcademy

INSTR returns the location of a substring in a string
INSTR( string, substring [, start_position [, th_appearance ] ] )
INSTR('Tech on the net', 'e')
Result: 2 (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 1)
Result: 2 (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 2)
Result: 11 (the second occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 3)
Result: 14 (the third occurrence of 'e')

INSTR('Tech on the net', 'e', -3, 2)
Result: 2

COALESCE Function  Allows you to return the first non-NULL value from a list of parameters
COALESCE ( expr1, expr2, [expr...] )
The downside is that it only transforms NULL values. It can't change other values, such as 0, or advanced logic;

select coalesce (valye1,value2,value3,'Y') from 
(select NULL as value1 Null asvalue2,'3' as value3 from duel);

DECODE Function  Allows you to have IF-THEN-ELSE logic in your SQL statements.
DECODE ( expression, search, result [, search, result]... [,default] )

Oracle-Relational Database

  • Database in which all data is stored in Relations (Tables) with     rows and columns. Each table is composed of records (called Tuples) and each record is identified by a field (attribute) containing a unique value. Every table shares at least one field with another table in 'one to one,' 'one to many,' or 'many to many' relationships. These relationships allow the database user to access the data in almost an unlimited number of ways, and to combine the tables as building blocks to create complex and very large databases.
  • The oracle database houses everything There is 1 database which has multiple tablespaces, schemas, Datafiles and segments.
What is Oracle Schema ??

•In simple terms a schema in an Oracle database is another name for a user. So a schema and a user are the same thing.
•SCHEMA = USER
•The purpose of a schema in Oracle is to house database objects. The objects could be like tables and indexes, or object definitions like views, packages, triggers, etc. Hopefully image will help you to understand the relationship between a database, a schema, the segments in a schema and the tablespace in which the segments reside.
More about Schema !!!

•A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of links
•Database triggers
•Dimensions
•External procedure libraries
•Indexes and index types
•Java classes
•Materialized views and materialized view logs
•Object tables, object types, and object views
•Operators
•Sequences
•Stored functions, procedures, and packages
•Synonyms
•Tables and index-organized tables
•Views

Logical Storage Structures
Oracle Database uses a logical storage structure for fine-grained control of disk space usage. The following are logical storage structures in an Oracle Database:
Data blocks: a data block corresponds to a number of bytes on the disk. Oracle stores data in data blocks. Data blocks are also referred to as logical blocks, Oracle blocks or pages.
Extents: An extent is a specific number of logically contiguous data blocks used to store the particular type of information.
Segments: a segment is a set of extents allocated for storing database objects, e.g., a table or an index.
Tablespaces: a database is divided into logical storage units called tablespaces. A tablespace is a logical container for a segment. Each tablespace consists of at least one data file.


     CONSTRAINTS IN ORACLE

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
  • NOT NULL - Ensures that a column cannot have a NULL value
  • UNIQUE - Ensures that all values in a column are different
  • PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
  • FOREIGN KEY - Uniquely identifies a row/record in another table
  • CHECK - Ensures that all values in a column satisfies a specific condition
  • DEFAULT - Sets a default value for a column when no value is specified
  • INDEX - Used to create and retrieve data from the database very quickly


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are remove
  • RENAME - rename an object
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update) EXEC - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
Data Control Language (DCL) Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

Angular Forms

Forms
  • Working with html forms
Template driven forms
  • Form directives
  • Form validation
  • Form CSS state classes
  • One way and bidirectional form data binding
  • Custom form validation
Reactive forms
  • Form services 
  • Form validation
  • Form directives
  • Custom form validation
  • Nested forms 
  • Updating form values
Comparison between Template driven and Reactive forms

Template driven forms
  • ngForm directive
  • ngModel directive
  • Form Validation
  • required
  • Form css state classes

  • ng-untouched / ng-touched
  • ng-pristine / ng-dirty
  • ng-invalid / ng-valid

Template driven forms

Form Validation continue…
  • required
  • minlength
  • maxlength
  • email
  • pattern

One way and Bidirectional data binding
  • ngModelChange
  • [(ngModel)]
Write a custom form field validator function
  • Create custom validator factory function
  • Create custom directive and link factory function
  • Register directive as form field validation directive
Reactive forms
FormGroup - tracks the values and validation status for a collection of form controls.
FormControl - tracks the value and validation status of an individual form control.
Form Validation
  • required
  • email
  • minlength
Link form with template
  • formGroup directive
  • formControlName directive
Custom form validation
  • formControl directive
  • app password strength validator
Form Builder angular service API
  • FormBuilder
  • add validation error messages
Creating nested form groups
Updating parts of the data model
  • setValue() – to set a new value for an individual control
  • patchValue() – to replace values for multiple controls
Creating dynamic forms
  • Form Array
Comparison between Template driven and Reactive forms

Template driven forms
  • Template-driven forms rely on directives in the template to create and manipulate the underlying object model. 
  • They are useful for adding a simple form to an app, such as an email list signup form. 
  • They're easy to add to an app, but they don't scale as well as reactive forms. 
  • If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

Reactive forms

  • Reactive forms provide direct, explicit access to the underlying forms object model. 
  • Compared to template-driven forms, they are more robust: 
  • they're more scalable, reusable, and testable. 
  • If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms


Monday 19 April 2021

Types of Directives, Built-In Directives, Custom Directives ,Ng-container Introduction to Pipes Built-In ,Pipes Custom Pipes

  • Introduction to Directives
  • Types of Directives
  • Built-In Directives
  • Custom Directives
  • Ng-container
  • Introduction to Pipes
  • Built-In Pipes
  • Custom Pipes
What are Directives ?
  • Directives are the Document Object Model (DOM) instruction sets, which decide how logic implementation can be done.
  • They add additional behavior to elements in your Angular applications.
  • These are Typescript class which is declared with decorator @Directive or @Component.
  • Based on Type of operation that can be performed , Directives are further classified into:  
  • Component Directive 
  • Attribute Directive
  • Structural Directive

Component Directive

  • Created with @Component Decorator.
  • This type of directive is the most common directive type.
  • Only type of directives which have a view attached i.e they have a template associated.
Attribute Directive

  • Attribute directives deal with changing the look and behavior of an element, component, or another directive.

When to use ?

  • These are used when we  want logic or events to change the appearance or behavior of the view.
  • When we have a UI element that will be common throughout our app, we can implement an attribute directive and share it across components and modules to avoid repeating the code for the same functionality.

Built-in Attribute Directive
  • NgClass - add or remove multiple CSS classes simultaneously based on condition within ngClass.
  • NgStyle – used to set multiple inline styles simultaneously, based on the state of the component.
  • NgModel—adds two-way data binding to an HTML form element.
Structural Directive
  • These are responsible for rendering the HTML layout.
  • Structural directives shape or reshape the DOM’ structure typically by adding, removing, or manipulating elements.
  • Identifier for a structural directives are (*). The asterisk is actually short for ng-template with the attribute passed in.

Built in Structural Directives
  • *ngIf - ngIf is used to display or hide the DOM Element based on the expression value assigned to it. The expression value may be either true or false.
  • *ngIf-else - ngIf-else works like a simple If-else statement, wherein if the condition is true then ‘If’ DOM element is rendered, else the other DOM Element is rendered. Angular uses ng-template with element selector in order to display the else section on DOM.
  • *ngFor - *ngFor is used to loop through the dynamic lists in the DOM. Simply, it is used to build data presentation lists and tables in HTML DOM.
  • *ngSwitch - ngSwitch is used to choose between multiple case statements defined by the expressions inside the *ngSwitchCase and display on the DOM Element according to that. If no expression is matched, the default case DOM Element is displayed. 
Peculiar use case
  • Use case - Sometimes , there occurs a need where in we need to use two structural directives simultaneously. We need to hide and show a grid and within the grid we want to iterate over the list.
  • Alert Point!!!!!.....We can’t use two structural directives in the same DOM element.
  • Solution :Not so elegant solution – Use two different HTML tag , one with ngIf and other with ngFor. Unnecessary Dom addition , which can affect the layout.
  • Elegant Solution – use ng-container
Few words about ng-container
  • It allows us to create a division or section in a template without introducing a new HTML element.
  • It is not render in the DOM, but content inside it is rendered.
  • It is just a syntax element , which is rendered as a comment.
Custom Directives


What are Pipes ?

      • A pipe is a way to write display-value transformations that you can declare in your HTML. It takes in data as input and transforms it to a desired output.
      • Please note – Pipe only change the display value and not the real time values , they remain as it is.
      • Use Case : Alter Date format in display or make a text uppercase


Default Pipes
  • Angular provides number of default pipes which suffices many of the requirements.
  • Exhaustive list is present at https://angular.io/api/common#pipes.
How to use : 
  • To apply a pipe, use the pipe operator (|) within a template expression as shown in the following code example, along with the name of the pipe. Also ,we can pass multiple parameters by using colon.
  • Few Examples : 
Custom Pipes

@Pipe({
name: 'truncateText'
})

<span>
{{longString | truncateText : 12 : 18}}
</span>

transform(value: string, startLen , endLen): unknown {
return `${value.substr(startLen,endLen)}...`;
}


<p>{{ 'angular' | uppercase }}</p>   //ANGULAR
<p>{{ 0.123456 | percent }}</p>  // 12%





Angular Router ? Components, routes and paths ? Steps to setup basic Routing demo

  • Intro to Angular Router
  • The Components, routes and paths
  • The router outlet
  • The routerLink directive (replaces the href attribute)
  • Steps to setup basic Routing demo
  • Route parameters
  • Query parameters
  • Route guards
  • Feature Module
  • Lazy Loading
  • Route resolvers
Introducing the Angular Router
  • The Angular router is an essential element of the Angular platform. 
  • It allows developers to build Single Page Applications with multiple states and views using routes and components and allows client side navigation and routing between the various components.
Routes and Paths

In Angular, a route is an object (instance of Route) that provides information about which component maps to a specific path. A path is the fragment of a URL that determines where exactly is located the resource (or page) you want to access.

Each route can have the following properties:

Path-: is a string that specifies the path of the route.

pathMatch-: is a string that specifies the matching strategy. It can take prefix (default) or full.
Component-: is a component type that specifies the component that should be mapped to the route.
redirectTo-: is the URL fragment which you will be redirected to if a route is matched.

Ex-: { path: 'my/path/', component: MyComponent }
{ path: '',  redirectTo: '/products', pathMatch: 'full' }

The Router Outlet
The Router-Outlet is a directive exported by RouterModule and acts as a placeholder that indicates to the router where it needs to insert the matched component(s). 

Ex-: <router-outlet></router-outlet>

RouterLink, Navigate and NavigateByUrl
you need to do is to add the navigation links that take you from one component to another.

Angular provides the routerLink and routerLinkActive directives that need to be added to the <a> anchors.

The routerLink directive needs to used instead of the href attribute.
The routerLinkActive directive is used to add a CSS class to an element when the link's route becomes active.
Ex-: <a [routerLink] = "'/products'">
  Go to Products List
</a>

router.navigate(['/‘,’products’])
router.navigateByUrl('/products')

Steps to setup basic Routing

The following command uses the Angular CLI to generate a basic Angular app with an app routing module, called AppRoutingModule, which is an NgModule where you can configure your routes.
New Project
i) ng new routing-app 
    After that it asks for Would you like to add Angular routing? y
ii) ng new routing-app --routing

In Existing Project want to add routing
iii) ng generate module app-routing --module app --flat


//app-routing.module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; 

const routes: Routes = [
{ path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent },
{ path: '**', component: PageNotFoundComponent }
]; 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }





<!--app.component-->
<h1>Angular Router App</h1>
<!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in  AppRoutingModule) -->
<nav>
  <ul>
    <li><a routerLink="/first-component" routerLinkActive="active">First Component</a></li>
    <li><a routerLink="/second-component" routerLinkActive="active">Second Component</a></li>
  </ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>

Route Parameters/Query Parameter
Dynamic routes are often used in web applications to pass data (parameters) or state to the application or between various components and pages. The Angular router has support for dynamic paths and provides an easy to use API to access route parameters.

Ex-: {path: 'product/:id' , component: ProductDetailComponent}

Getting route information

We can get this through ActivatedRoute -Provides access to information about a route associated with a component that is loaded in an outlet. 

Route Parameters/Query Parameter
Dynamic routes are often used in web applications to pass data (parameters) or state to the application or between various components and pages. The Angular router has support for dynamic paths and provides an easy to use API to access route parameters.

Ex-: {path: 'product/:id' , component: ProductDetailComponent}

Getting route information

We can get this through ActivatedRoute -Provides access to information about a route associated with a component that is loaded in an outlet. 

Ex-: Two ways  route parameter 1) this.route.snapshot.paramMap.get('id');
2) this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id'));})
3) this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
4) this.route.snapshot.params.param1;

Angular Route Guards
Route guards enables you to allow or disallow access to your specific application routes based on some criteria (for example if the user is logged in or not).

Feature modules
A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms. While you can do everything within the root module, feature modules help you partition the app into focused areas.

Lazy-loading feature modules

By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.


Ex-: Step 1) const routes: Routes = [  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];

2) const routes: Routes = [ { path: '', component: CustomersComponent } ]; 
@NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) 
export class CustomersRoutingModule { }
3) @NgModule({
 imports: [ CommonModule, CustomersRoutingModule ], 
declarations: [CustomersComponent] }) 
export class CustomersModule { }

Resolver
To preload component data, we can use a resolver. Resolvers improve UX by blocking the page load until all necessary data is available to fully display the page.

Steps to create
Define Service
export class CrisisDetailResolverService implements Resolve<> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<> {
// your logic goes here
}
}

2) Import this resolver into your module's routing module.
{ path: '/your-path', component: YourComponent, resolve: { crisis: YourResolverService } }
3) In the component, use an Observable to get the data from the ActivatedRoute.





What is Data Binding ? Types of Data Binding ? Communication between Parent Child Components


Data Binding



  • Components
             Decorator
             Metadata
  • Cycle Hooks
          ngOnChanges
          ngOnInit 
          ngDoCheck 
             ngAfterContentInit
             ngAfterContentChecked
             ngAfterViewInit 
             ngAfterViewChecked 
  • ngOnDestroy
Description
  • Components are the most basic UI building block of an Angular app.
  • An Angular app contains a tree of Angular components.
  • Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.
  • A component must belong to an NgModule in order for it to be available to another component or application. To make it a member of an NgModule, list it in the declarations field of the NgModule metadata.
Components are a logical piece of code for Angular JS application. A Component consists of the following-
Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.

Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript.

Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.

@Component ({
   selector: 'my-app',
   template: ` <div><h1>{{appTitle}}</h1><div>To Tutorials Point</div> </div> `,
})

Option

Description

changeDetection?

The change-detection strategy to use for this component.

viewProviders?

Defines the set of injectable objects that are visible to its view DOM children. See example.

moduleId?

The module ID of the module that contains the component. The component must be able to resolve relative URLs for templates and styles. SystemJS exposes the __moduleName variable within each module. In CommonJS, this can be set to module.id.

templateUrl?

The relative path or absolute URL of a template file for an Angular component. If provided, do not supply an inline template using template.

template?

An inline template for an Angular component. If provided, do not supply a template file using templateUrl.

styleUrls?

One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component.

styles?

One or more inline CSS stylesheets to use in this component.

animations?

One or more animation trigger() calls, containing state() and transition() definitions. See the Animations guide and animations API documentation.

encapsulation?

An encapsulation policy for the template and CSS styles. One of:

ViewEncapsulation.Emulated: Use shimmed CSS that emulates the native behavior.
ViewEncapsulation.None: Use global CSS without any encapsulation.
ViewEncapsulation.ShadowDom: Use Shadow DOM v1 to encapsulate styles.

interpolation?

Overrides the default interpolation start and end delimiters ({{ and }}).

entryComponents?

A set of components that should be compiled along with this component. For each component listed here, Angular creates a ComponentFactory and stores it in the ComponentFactoryResolver.

preserveWhitespaces?

True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the \s character class in JavaScript regular expressions. Default is false, unless overridden in compiler options.



Following is a description of each lifecycle hook.
ngOnChanges − When the value of a data bound property changes, then this method is called.
ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own.
ngAfterContentInit − This is called in response after Angular projects external content into the component's view.
ngAfterContentChecked − This is called in response after Angular checks the content projected into the component.
ngAfterViewInit − This is called in response after Angular initializes the component's views and child views.
ngAfterViewChecked − This is called in response after Angular checks the component's views and child views.
ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component.

ngOnChanges – This event executes every time when a value of an input control within the component has been changed. Actually, this event is fired first when a value of a bound property has been changed. It always receives a change data map, containing the current and previous value of the bound property wrapped in a SimpleChange.

import { Component, OnChanges } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements OnChanges{
  constructor() {}

  ngOnChange() {
// console.log(“ print on change detections”)
}
}


ngOnInit – This event initializes after Angular first displays the data-bound properties or when the component has been initialized. This event is basically called only after the ngOnChanges()events. This event is mainly used for the initialize data in a component.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements OnInit {
  constructor() {}

  ngOnInit() {
// console.log(“ print on ngOnInit”)
}
}

ngDoCheck – This event is triggered every time the input properties of a component are checked. We can use this hook method to implement the check with our own logic check. Basically, this method allows us to implement our own custom change detection logic or algorithm for any component.

import { Component, DoCheck} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements DoCheck{
  constructor() {}

  ngDoCheck() {
// console.log(“ ngDoCheck”)
}
}


ngAfterContentInit – This lifecycle method is executed when Angular performs any content projection within the component views. This method executes when all the bindings of the component need to be checked for the first time. This event executes just after the ngDoCheck() method. This method is basically linked with the child component initializations.
import { Component, AfterContentInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements AfterContentInit {
  constructor() {}

 ngAfterContentInit () {
// console.log(“ngAfterContentInit ”)
}
}


ngAfterContentChecked – This lifecycle hook method executes every time the content of the component has been checked by the change detection mechanism of Angular. This method is called after the ngAfterContentInit() method. This method is also called on every subsequent execution of ngDoCheck(). This method is also mainly linked with the child component initializations.

import { Component, AfterContentChecked } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements AfterContentChecked {
  constructor() {}

 ngAfterContentChecked () {
// console.log(“ngAfterContentChecked ”)
}
}

ngAfterViewInit – This lifecycle hook method executes when the component’s view has been fully initialized. This method is initialized after Angular initializes the component’s view and child views. It is called after ngAfterContentChecked(). This lifecycle hook method only applies to components.

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements AfterViewInit {
  constructor() {}

 ngAfterViewInit () {
// console.log(“ngAfterViewInit ”)
}
}

ngAfterViewChecked – This method is called after the ngAterViewInit() method. It is executed every time the view of the given component has been checked by the change detection algorithm of Angular. This method executes after every subsequent execution of the ngAfterContentChecked(). This method also executes when any binding of the children directives has been changed. So this method is very useful when the component waits for some value which is coming from its child components.
import { Component, AfterViewChecked } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements AfterViewChecked {
  constructor() {}

 ngAfterViewChecked () {
// console.log(“ngAfterViewChecked ”)
}
}

ngOnDestroy – This method will be executed just before Angular destroys the components. This method is very useful for unsubscribing from the observables and detaching the event handlers to avoid memory leaks. Actually, it is called just before the instance of the component is finally destroyed. This method is called just before the component is removed from the DOM.
import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html‘,
  styleUrl: ‘ ./app.component.css’
})
export class AppComponent implements OnDestroy {
  constructor() {}

   ngOnDestroy() {
    console.log('Component Destroy');
  }
}




What is Angular CLI ? Angular CLI Commands ? Basic Project structure ? What is Mono Repo Pattern?

What is Angular CLI ? Angular CLI Commands ? Basic Project structure ? What is Mono Repo Pattern?

  • The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell
  • npm install -g @angular/cli
  • Online help is available on the command line
  • ng help 
  • ng generate –help
  • To create, build, and serve a new, basic Angular project on a development server
  • ng new my-first-project 
  • cd my-first-project 
  • ng serve


                    

COMMAND

ALIAS

DESCRIPTION

add

 

Adds support for an external library to your project.

analytics

 

Configures the gathering of Angular CLI usage metrics

build

b

Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.

config

 

Retrieves or sets Angular configuration values in the angular.json file for the workspace.

deploy

 

Invokes the deploy builder for a specified project or for the default project in the workspace.

doc

d

Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.

e2e

e

Builds and serves an Angular app, then runs end-to-end tests using Protractor.

extract-i18n

i18n-extract xi18n

Extracts i18n messages from source code.

generate

g

Generates and/or modifies files based on a schematic.

help

 

Lists available commands and their short descriptions.

lint

l

Runs linting tools on Angular app code in a given project folder.

new

n

Creates a new workspace and an initial Angular application.

run

 

Runs an Architect target with an optional custom builder configuration defined in your project.

serve

s

Builds and serves your app, rebuilding on file changes.

test

t

Runs unit tests in a project.

update

 

Updates your application and its dependencies. See https://update.angular.io/

version

v

Outputs Angular CLI version.


WORKSPACE CONFIG FILES

PURPOSE

angular.json

CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses, such as TSLintKarma, and Protractor. For details, see Angular Workspace Configuration.

package.json

Configures npm package dependencies that are available to all projects in the workspace. See npm documentation for the specific format and contents of this file.

package-lock.json

Provides version information for all packages installed into node_modules by the npm client. See npm documentation for details. If you use the yarn client, this file will be yarn.lock instead.

src/

Source files for the root-level application project.

node_modules/

Provides npm packages to the entire workspace. Workspace-wide node_modules dependencies are visible to all projects.

tsconfig.json

The base TypeScript configuration for projects in the workspace. All other configuration files inherit from this base file. For more information, see the Configuration inheritance with extends section of the TypeScript documentation.

tslint.json

Default TSLint configuration for projects in the workspace.

Mono Repo :

  • The Monorepo, as the name suggests mono (single) and repo (repository of the codebase) is a single source of truth for the entire organization code base.


Angular Workspace can be divided into sub-projects which are categorized into:
Standalone Sub-project(s) - These are standalone projects which hold modules/components falling under one set of business functionality or domain. 
Integration Sub-Project(s)- These primarily work as integration project which consolidates bits and pieces from standalone and library projects and serves it as a web-application.
Library Sub-Project(s) - The library sub-projects hold any components/modules/directive/pipes/interceptors that may be used in more than on sub-project or integration project.