1.Difference between ViewChild & ViewChildren
The @ViewChild and @ViewChildren decorators in Angular provide a way to access and manipulate DOM elements, directives and components.
You can use ViewChild if you need to query one element from the DOM and ViewChildren for multiple elements.
ViewChild is a decorator that creates a view or DOM query.
selector – the selector of the element to query. This can be a directive type or a name.
ViewChild can take the following selectors:
Classes with the @Component or @Directive decorators i.e components and directives,
Template reference variables,
Providers,
TemplateRef
I. Whate is ViewChid
Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.
1) Accesss and manipulate Components & Elements:
latest.component.html
<span #somecontent>Some Content</span>
latest.component.ts
import { Component, OnInit, ViewChild, AfterContentInit, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-latest',
templateUrl: './latest.component.html'
})
export class LatestComponent implements OnInit, AfterViewInit {
@ViewChild('somecontent') somecontent : ElementRef;
ngOnInit(){}
ngAfterViewInit(){
console.log(this.somecontent.nativeElement)
}
}
- Give the reference name for the element in component template (view)
- ViewChild – Serach for the element inside the view, the first parameter is the reference which we need to search. If it has more than once , it give us the first one.
- Viewchildren will be created after ngAfterViewInit, ngAfterViewChecked
- nativeElement property will return the Dom element
- ViewChild will return the Type of the viewchild variable will be ElementRef
Example 2 : If we want get the viewChild of component which we used within the parent component
parent : latest.component.html
<app-date-viewer></app-date-viewer>
child : date-viewer.component.html
<span>{{today}}</span>
Child : date-viewer.component.ts
import { Component, OnInit, ViewChild, AfterContentInit, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-date-viewer',
templateUrl: './date-viewer.component.html'
})
export class DateViewerComponent implements OnInit, AfterViewInit {
today: Date = new Date();
ngOnInit(){}
ngAfterViewInit(){
//console.log(this.somecontent.nativeElement)
}
}
parent : latest.component.ts
import { Component, OnInit, ViewChild, AfterContentInit, ElementRef, AfterViewInit } from '@angular/core';
import {DateViewerComponent} from './date-viewer.component';
@Component({
selector: 'app-latest',
templateUrl: './latest.component.html'
})
export class LatestComponent implements OnInit, AfterViewInit {
@ViewChild(DateViewerComponent) dateViewRef : DateViewerComponent;
ngOnInit(){}
ngAfterViewInit(){
console.log(this.dateViewRef);
setInterval(()=>{
this.dateViewRef.today = new Date();
},2000)
}
}
- ngAfterViewChecked triggered whenever value changes in the date-viewer component
- ngAfterViewInit will triggered only once after the view is initialized (children is initialized)
Example 3 : What will if we have multiple children components
Parent : latest.component.html
<app-date-viewer></app-date-viewer>
<br/>
<br/>
<app-date-viewer></app-date-viewer>
Parent : latest.component.ts
import { Component, OnInit, ViewChild, AfterContentInit, ElementRef, AfterViewInit, ViewChildren, QueryList } from '@angular/core';
import {DateViewerComponent} from './date-viewer.component';
@Component({
selector: 'app-latest',
templateUrl: './latest.component.html'
})
export class LatestComponent implements OnInit, AfterViewInit {
@ViewChildren(DateViewerComponent) dateViewRef : QueryList;
ngOnInit(){}
ngAfterViewInit(){
console.log(this.dateViewRef);
console.log(this.dateViewRef.toArray()); //To get QueryList in array use toArray()
this.dateViewRef.toArray().forEach((element)=>{
setInterval(()=>{
element.today = new Date();
},2000)
})
}
}
- To get multiple children component we can use ViewChildren decorator
- ViewChildren will return List of elements
- We need to use QueryList to get list of components
====
We can access any properties and even methods from the queried component.
2) Querying Standard HTML Elements with Angular Template References :
We can also query standard HTML elements using ViewChild and template reference variables.
We import ElementRef and we create a query configuration to access the
DOM element with the #pRef template reference as follows:
@ViewChild('pRef', {static: false}) pRef: ElementRef;
ngAfterViewInit() {
console.log(this.pRef.nativeElement.innerHTML);
this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!";
}
II. ViewChildren in Angular
==========================
ViewChildren is another property decorator which is used to query the DOM for multiple elements and return a QueryList.
You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.
Example :
<hello name="Angular 6" ></hello>
<hello name="Angular 7" ></hello>
<hello name="Angular 8" ></hello>
<hello name="Angular 9" ></hello>
@ViewChildren(HelloComponent) hellos: QueryList;
ngAfterViewInit() {
this.hellos.forEach(hello => console.log(hello));
}
conclusion :
how we can access and modify the DOM in Angular 9 using ViewChild and ViewChildren decorators and a couple of other APIs like QueryList and ngAfterViewInit()
2. DIFFERENCE BETWEEN COMPONENT AND DIRECTIVE IN ANGULAR 2 ?
Structural directives
Like *ngFor and *ngIf, used to change the DOM layout by adding and removing DOM elements.
Attribute directives
They are used to give custom behavior or style to the existing elements by applying some functions/logic.
Components:
@Component meta-data annotation is used to register the components.
The components are used to create UI widgets.
The components are used to split to application into smaller parts.
Only one component is used per DOM element.
In the components, @View, template and templateUrl are mandatory in the components.
Directive:
@Directive meta-data annotation is used to register the directives.
The directives are used to add behavior to existing DOM elements.
The directives are use to design a reusable components.
More than one directive are used per DOM element.
The directive do not have @View etc.
3.Difference between Pure and Impure Pipe
Pure :
1.A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe.
For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
3.A single instance of the pure pipe is used all over the components.
pipeTransform
//Example 1 : Step 1 - Create Custom Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'employeeTitle'
})
export class EmployeeTitlePipe implements PipeTransform {
transform(value: string, gender: string): string {
if (gender.toLowerCase() == "male")
return "Mr." + value;
else
return "Miss." + value;
}
}
Step 2 : Register "EmployeeTitlePipe" in the angular module where we need it.import the EmployeeTitlePipe and include it in the "declarations" array of NgModule decorator
Step3 :
<tr *ngFor='let employee of employees;'>
<td>{{employee.code}}</td>
<td>{{employee.name | employeeTitle:employee.gender}}</td>
<td>{{employee.gender}}</td>
</tr>
@Pipe({
name : 'employeeFilter'
})
export class EmployeePipeFilter implements pipeTransform {
transform(employees: Employee[], searchTerm: string) : Employees[] {
if(!employees || !searchTerm){
return employees
}
return employees.filter(employee => employee.name.toLowerCase().indexOf(searchTerm) !=-1)
}
}
Chaining pipes :
We can chain multiple pipes together. This particularly helps in scenarios where we need to associate more than one pipe that needs to be applied, and the final output will be transformed with all the pipes applied.
The workflow or chains will be triggered and apply the pipes one after another. An example of the chain pipe syntax is given as follows:
{{today | date | uppercase | slice:0:4}}
Impure :
1. An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.
2. An impure pipe is called on every change detection cycle in Angular
what-is-pure-and-impure-pipes
What are pipes
4.Difference between Observable and Promise
Promises and Observables both handle the asynchronous call only.
Observable
Emits multiple values over a period of time
Is not called until we subscribe to the Observable
Can be canceled by using the unsubscribe() method
Provides the map, forEach, filter, reduce, retry, and retryWhen operators
//Service.ts
getEmployeeByCode(empCode: string): Observable<IEmployee> {
return this._http.get("http://localhost:31324/api/employees/" + empCode)
.map((response: Response) => <IEmployee>response.json())
.catch(this.handleError);
}
//component.ts
this._employeeService.getEmployeeByCode(empCode)
.subscribe((employeeData) => {
if (employeeData == null) {
this.statusMessage =
'Employee with the specified Employee Code does not exist';
}
else {
this.employee = employeeData;
}
},
(error) => {
this.statusMessage =
'Problem with the service. Please try again after sometime';
console.error(error);
});
Promise
Emits only a single value at a time
Calls the services without .then and .catch
Cannot be canceled
Does not provide any operators
//service.ts
getEmployeeByCode(empCode: string): Promise<IEmployee> {
return this._http.get("http://localhost:31324/api/employees/" + empCode)
.map((response: Response) => <IEmployee>response.json())
.toPromise()
.catch(this.handlePromiseError);
}
//component.ts
this._employeeService.getEmployeeByCode(empCode)
.then((employeeData) => {
if (employeeData == null) {
this.statusMessage =
'Employee with the specified Employee Code does not exist';
}
else {
this.employee = employeeData;
}
},
(error) => {
this.statusMessage =
'Problem with the service. Please try again after sometime';
console.error(error);
});
(Promise)Emits a single value (Observable)Emits multiple values over a period of time
(Promise)Not Lazy (Observable)Lazy. An Observable is not called until we subscribe to the Observable
(Promise)Cannot be cancelled (Observable)Can be cancelled using the unsubscribe() method
(Observable) provides operators like map, forEach, filter, reduce, retry, retryWhen etc.
angular-promises-vs-observables
what-is-the-difference-between-promises-and-observables
5.AOT and JIT
AOT – Ahead of time compilation – compile the application at build time (it is pre compiled)
– Errors are come to know at build time
ng build -aot
ng serve -aot
Turn off production build in AOT
ng build –prod –aot false
JIT (Development) – Just in time compilation – compile the application just in time in the browser runtime
– The application code along with the angular compiler is downloaded by browser.
– Template binding errors are only know at run time
ng build
ng serve
4.Difference between arrow function and regular function
There are 3 subtle differences in regular functions and arrow functions in JavaScript.
1. No own this bindings
2. Arrow functions do not have a arguments array
3. Arrow functions are callable but not construct able
1. No own this bindings
Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
2.Arrow functions do not have a arguments array
In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope.
3.Arrow functions are callable but not construct able
If a function is construct able, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).
Functions created through function declarations / expressions are both construct able and callable.
Arrow functions (and methods) are only callable. class constructors are only construct able.
If you are trying to call a non-callable function or to construct a non-construct able function, you will get a run time error.
Dependency Injection
Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation.
Dependency injection in Angular
Dependency injection (DI), is an important application design pattern. Angular has its own DI framework, which is typically used in the design of Angular applications to increase their efficiency and modularity.
Dependencies are services or objects that a class needs to perform its function. DI is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself.
In Angular, the DI framework provides declared dependencies to a class when that class is instantiated. This guide explains how DI works in Angular, and how you use it to make your apps flexible, efficient, and robust, as well as testable and maintainable.
Angular dependency injection – Text
Angular dependency injection – Video
What is Dependency Injection :
It’s a coding pattern in which a class receives its dependencies from an external source rather than creating them itself.
DI provides these benefits :
Create applications that are easy to write and maintain over time as the application evolves
Easy to share data and functionality as the angular injector provides a Singleton i.e a single instance of the service
Easy to write and maintain unit tests as the dependencies can be mocked
How dependency injection works in angular :
When a component in Angular needs a service instance, it does not explicitly create it. Instead it just specifies it has a dependency on a service and needs an instance of it by including the service as a constructor parameter.
When an instance of the component is created, the angular injector creates an instance of the service class and provides it to component constructor.
So the component which is dependent on a service instance, receives the instance from an external source rather than creating it itself. This is called Dependency Injection.
why-dependency-injection – Text
why-dependency-injection – Video
Angular Singleton Service
angular-2-tutorial-for-beginners
32. Angular dependency injection | Text | Slides
33. Why dependency injection | Text | Slides
34. Angular singleton service | Text | Slides
35. Angular Injector | Text | Slides
36. Angular root injector | Text | Slides
dependency-injection-aungular.io
5.What is Angular ?
Angular is a JavaScript framework which used to create and develop single-page applications.In practice, angular extends HTML attributes with Directives and binds data to HTML with expressions.
It is true that web-based applications have become more secure and customizable due to angular. It has made the applications scalable, flexible and highly secure
difference-among-angular-8-7-6-5-4-3-2
AngularJS :
It uses the controller approach where the view communicates using a $scope.
Angular JS does not support mobile devices
while this is not in the case of AngularJS that makes them unique from each other.
Angular 2 :
It uses the component based approach.
while Angular 2 does support all mobile devices.
There are more language choices in Angular 2 like Dart, JavaScript, TypeScript, Elm and PureScript etc
Differences Between Angular 2 And Angular 4
it comes with better performance values, better resources, better user-interaction features, smoother results, least commotions, and the faster reflexes etc.
Angular 2 and Angular 4 both are the enhanced size of AoT or ahead-of-time and have compiler generated code. Due to compiler generated code, Angular 4 has become smoother and swift than the Angular JS 2.
Angular 2 supports TypeScript 1.8 version, whereas Angular 4 supports typescript 2.1 and 2.2 versions.
In Angular 4, user can use “else” block along with “*ngif” block, example is given below how it works actually:
Angular 2 :
<div *ngIf=”Condition”>
<h2>Condition true!</h2>
</div>
<div *ngIf=”!Condition”>
<h2>Condition false!</h2>
</div>
Angular 4 :
<div *ngIf=”Condition; else runFalsyTemplate”>
<h2>Condition true!</h2>
</div>
<ng-template #runFalsyTemplate>
<h2>Condition false!</h2>
</ng-template>
Angular 2 and Angular 6
The biggest changes are probably the router and the http-coomunication.
The HttpModule has been replaced by the HttpClientModule, which is easier to use and has a few more features.
We have the Angular CLI, a powerfull command line tool, which helps you create, run, test and deploy applications.
We have the Angular CDK, a component development kit, which helps you create high quality components.
We have Angular Material, a material design library build on top of the CDK.
We have support for service-workers and PWAs.
We have Angular Universal, which allowes you to pre-render the page on the server.
Bundle size in angular 6 is reduced and load time of application is also improved.
Angular 2 have typscript 2.1 support and angular 6 have latest typescript 2.7+
Angular 2 Don’t have support of native element and angular 6 comes with added to support of native element
1. ng add:
This new CLI command ng add
ng add will use your package manager to download new dependencies and invoke an installation script which can update the project with configuration changes, add additional dependencies.
2. ng update:
ng update
It will help you adopt the right version of dependencies, and keep your dependencies in sync.
Most notable change is rxjs 6. Also, the old APIs still work by the way.