Angular
Angular
It has several enhancements on top of Angular 1.x, which makes it simple to use and get the desired
output. But knowledge in Angular 1.x is not necessary to learn Angular 2, since the whole framework is
re-written.
Why Angular 2?
Easy: Unlike previous versions, Angular 2 focuses only on building JavaScript classes; hence it is easier to
learn.
Freedom: It provides more choices of languages for consumption i.e. ES5, ES6, Typescript, and Dart.
TypeScript is recommended here.
To setup an Angular 2 environment, node.js is mandatory. Once node.js and npm are available, you can
run the following to complete the setup in cmd.
Install Angular CLI(command line interface) Command: npm i -g @angular/cli (-g installs angular globally
for all users)
There can be several Modules within an app, but it should consist of at least one root module. Root
Module, by convention, must be named: AppModule.
Module as library - Angular Module can act as a library of modules. @angular/core is a most common
library being used in building angular application. It has most of the modules that are required for your
app.
Module - Example
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
Trick to identify Root Module is that it imports "BrowserModule". Other modules of that same
application imports "CommonModule".
declarations:[...] - define components, directives and pipes for this module here.
What is Component?
It handles the view part of the app and has the core logic of the page.
There can be only one component per DOM element (i.e. only one selector element).
Element's behavior can be manipulated by the properties associated with corresponding component.
Components can be created, updated or destroyed based on the user actions on the page.
Components - Example
This example will render Hello, World! in the browser. Angular will search for <my-app> element in HTML
file and replace it with the template content.
File: app.component.ts
@Component({
selector: 'my-app',
})
File: index.html
............
<body>
</body>
............
What is Template?
Template is a simple HTML code that creates view for a component, which you can dynamically
manipulate.
template
templateUrl
@Component({
selector: 'greet',
template: `
//this defines template for 'greet' component
<h1>Hello There!!!</h1>
})
When templateUrl is used, the code is defined in different files and URL of the corresponding files are
referred.
@Component({
selector: 'greet',
templateUrl: 'app.component.html'
})
What is Metadata?
In Angular 2, Metadata is vital in getting the code processed and shown on the screen. Metadata means
data of data, which gives more info about data.
// 20 is data
// "number" is metadata, as it tells information of "data", its type, its size etc.
Metadata - Example
Let us consider a simple example code as shown below. Suppose you want to have a component,
Angular will consider it as a simple "class" until you explicitly use "Decorator" and attach metadata to
TypeScript.
@Component({ //METADATA
selector: 'greet',
template: `
<h1>Hello There!!!</h1>
})
Simply put, everything in Angular 2 is a simple class, until you declare metadata (@Component or @Pipe
or @Decorator or @Injectable) to it.
It is the process of automatic synchronization of view and business logic. It helps in connecting the
Template (view - what user sees) with Component (back end data/source).
There are four ways you can bind a data to the DOM depending on the direction the data flows.
Data flows outside the view into the class by Event Binding.
Interpolation
Interpolation acts as local variable, which allows us to bind data from "Component Class" onto your
"Template".
Both are same, as they make the data flow from "Component" to "Template". The only difference is the
way they are defined or used.
Interpolation Demo
@Component ({
selector: 'myApp',
template: `
})
@Component ({
selector: 'myApp',
template: `
})
Event Binding
User interaction on view generates "Events" that make data flow from "Template" to "Component". It is
defined using () parantheses. The following video will explain Event Binding in detail.
Property Binding and Event Binding are One Way Data Binding. In other words, data will flow either from
Component to View or the other way, but not both.
Two-way data binding is a combination of both Property Binding and Event Binding allowing us to update
data in both directions. It is defined using [( )] popularly known as banana brackets.
Directive is a class with @Directive decorator. They make DOM elements dynamic, by changing their
behavior.
Structural Directive
They manipulate the DOM elements. i.e. Delete or update the elements. This changes the structure of
webpage.
Some of the built-in structural directives, Angular 2 offers are NgIf, NgFor and NgSwitch.
Attribute Directive
These directives add styling by manipulating the Attributes of DOM element. They do not change the
structure of webpage.
NgStyle and NgClass are some of the built-in attribute directives, Angular 2 provides.
Technically Components is a subset of directives except the fact that they have a mandatory template
parameter.
What is Service?
Services are functions that are designed to complete a specific task. If you want to bring external data
from server into your app or perform some repetitive task, then services come handy.
Create a class with the required function and use the decorator @injectable() to specify that it is
a service.
Then import the service in root component, which is discussed in Dependency Injection.
Example: This simple service will perform add operation whenever it is used.
@Injectable()
Dependency Injection is a way to "Inject" the parameters or services (dependencies), on which the new
Instance is "Dependent" for its creation. How the dependencies are created is not a point of concern for
the instance consuming the dependency.
Angular finds which services are required to the component, by looking at the "type" of
component's constructor parameters.
Angular then checks for the service in Injector, which makes a container of all services that have
already been created.
You will learn more about Services and Dependency Injection in detail in a different course.
ngOnChanges() -> ngOnInit() -> ngDoCheck() -> ngAfterContentChecked() -> ngAfterViewInit() ->
ngOnDestroy()
Here's a breakdown of each lifecycle hook and its placement in the sequence:
1. ngOnChanges(): This hook is called whenever a data-bound input property of the component
changes. It's the first hook called after any input changes are detected.
2. ngOnInit(): This hook is called after the first ngOnChanges and only once after the component is
initialized. It's a good place to perform any initialization tasks that don't depend on DOM
elements.
3. ngDoCheck(): This hook is called after every change detection cycle, which can happen due to
various reasons like user interactions, external events, or asynchronous operations. It's generally
not recommended for heavy computations due to its frequent calls.
4. ngAfterContentChecked(): This hook is called after the content projected into the component's
view has been checked. This is useful for reacting to changes in projected content.
5. ngAfterViewInit(): This hook is called after the component's view (including projected content)
has been fully initialized. It's a good place to perform actions that require a fully rendered DOM,
like manipulating DOM elements or accessing child components using view queries.
6. ngOnDestroy(): This hook is called just before the component is destroyed. It's a good place to
perform any cleanup tasks like unsubscribing from subscriptions or releasing resources.
Remember that not all lifecycle hooks are mandatory, and you'll use them based on your component's
specific needs.
Metadata: Decorators that provide information about components, directives, and services.
Data Binding: Mechanism for synchronizing data between the component and the view.
Services: Reusable classes that encapsulate application logic and data access.
Router: