The angular interview is not so tough, you can just crack your interview in some easy way. you just have to follow these interview questions below and practice hard. This is a UI framework and some basic coding and you just need to practice these questions to enter the organization as well as for those who are experienced
Interview questions (45 to 103)
45. What is the difference between promise and observable?
Below is the list of differences between
promise and observable,
Observable
|
Promise
|
Declarative: Computation does not start until subscription so
that they can be run whenever you need the result
|
Execute immediately on creation
|
Provide multiple values over time
|
Provide only one
|
Subscribe method is used for error handling which makes
centralized and predictable error handling
|
Push errors to the child promises
|
Provides chaining and subscription to handle complex
applications
|
Uses only .then() clause
|
46. What is multicasting?
Multi-casting is the practice of broadcasting
to a list of multiple subscribers in a single execution. Let's demonstrate the
multi-casting feature,
var source = Rx.Observable.from([1, 2, 3]);
var subject = new Rx.Subject();
var multicasted = source.multicast(subject);
// These are, under the hood,
`subject.subscribe({...})`:
multicasted.subscribe({
next: (v) => console.log('observerA: ' + v)
});
multicasted.subscribe({
next: (v) => console.log('observerB: ' + v)
});
// This is, under the hood, `s
47. How do you perform error handling in observables?
You can handle errors by specifying an error callback on the observer instead of relying on
try/catch which is ineffective in the asynchronous environment. For example, you
can define error callback as below,
myObservable.subscribe({
next(num) { console.log('Next num: ' + num)},
error(err) { console.log('Received an errror: ' + err)}
});
48. What is the short hand notation for subscribe
method?
The subscribe() method can accept callback
function definitions inline, for next, error, and complete handlers is known
as shorthand notation or Subscribe method with positional arguments. For
example, you can define the subscribe method as below,
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
49. What are the utility functions provided by
RxJS?
The RxJS library also provides below utility
functions for creating and working with observables.
i.
Converting existing
code for async operations into observables
ii.
Iterating through the
values in a stream
iii.
Mapping values to
different types
iv.
Filtering streams
v.
Composing multiple
streams
50. What are observable creation functions?
RxJS provides creation functions for the
process of creating observables from things such as promises, events, timers, and Ajax requests. Let us explain each of them with an example,
i.
Create an observable
from a promise
import { from } from 'rxjs'; // from function
const data = from(fetch('/api/endpoint')); //Created from Promise
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error('Error: ' + err); },
complete() { console.log('Completed'); }
});
ii.
Create an observable
that creates an AJAX request
import { ajax } from 'rxjs/ajax'; // ajax function
const apiData = ajax('/api/data'); // Created from AJAX request
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));
iii.
Create an observable
from a counter
import { interval } from 'rxjs'; // interval function
const secondsCounter = interval(1000); // Created from
Counter value
secondsCounter.subscribe(n =>
console.log(`Counter value: ${n}`));
iv.
Create an observable
from an event
import { fromEvent } from 'rxjs';
const el = document.getElementById('custom-element');
const mouseMoves = fromEvent(el, 'mousemove');
const subscription = mouseMoves.subscribe((e: MouseEvent) => {
console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
});
51. What will happen if you do not supply handler
for observer?
Normally an observer object can define any
combination of next, error and complete notification type handlers. If you
don't supply a handler for a notification type, the observer just ignores
notifications of that type.
52. What are the angular elements?
Angular elements are Angular components
packaged as custom elements(a web standard for defining new HTML elements in a
framework-agnostic way). Angular Elements hosts an Angular component, providing
a bridge between the data and logic defined in the component and standard DOM
APIs, thus, providing a way to use Angular components in non-Angular environments.
53. What is the browser support of Angular
Elements?
Since Angular elements are packaged as custom
elements the browser support of angular elements is the same as custom elements
support. This feature is currently supported natively in a number of
browsers and pending for other browsers.
Browser
|
Angular Element Support
|
Chrome
|
Natively
supported
|
Opera
|
Natively
supported
|
Safari
|
Natively
supported
|
Firefox
|
Natively
supported from 63 version onwards. You need to enable
dom.webcomponents.enabled and dom.webcomponents.customelements.enabled in
older browsers
|
Edge
|
Currently
it is in progress
|
54. What are custom elements?
Custom elements (or Web Components) are a Web
Platform feature extends HTML by allowing you to define a tag whose
content is created and controlled by JavaScript code. The browser maintains
a CustomElementRegistry of defined custom elements, which maps an instantiable
JavaScript class to an HTML tag. Currently, this feature is supported by Chrome,
Firefox, Opera, and Safari, and available in other browsers through polyfills.
55. Do I need to bootstrap custom elements?
No, custom elements bootstrap (or start)
automatically when they are added to the DOM and are automatically destroyed
when removed from the DOM. Once a custom element is added to the DOM for any
page, it looks and behaves like any other HTML element, and does not require
any special knowledge of Angular.
56. Explain how custom elements work internally?
Below are the steps in order about custom
elements functionality,
iv.
App registers custom element with browser: Use the createCustomElement() function
to convert a component into a class that can be registered with the browser as
a custom element.
v.
App adds custom element to DOM: Add custom element just like a built-in
HTML element directly into the DOM.
vi.
Browser instantiate component based class: Browser creates an instance of the
registered class and adds it to the DOM.
vii.
Instance provides content with data binding and change
detection: The content with
in template is rendered using the component and DOM data. The flow chart of the
custom elements functionality would be as follows,
How
to transfer components to custom elements?
Transforming components to custom elements
involves two major steps,
.
Build custom element class: Angular provides the createCustomElement() function for converting an Angular
component (along with its dependencies) to a custom element. The conversion
process implements NgElementConstructor interface, and creates a constructor
class which is used to produce a self-bootstrapping instance of Angular component.
i.
Register element class with browser: It uses customElements.define() JS function, to register the configured constructor and
its associated custom-element tag with the browser's CustomElementRegistry. When the browser encounters the tag for the registered
element, it uses the constructor to create a custom-element instance. The
detailed structure would be as follows,
What
are the mapping rules between Angular component and the custom element?
The Component properties and logic maps
directly into HTML attributes and the browser's event system. Let us describe
them in two steps,
.
The
createCustomElement() API parses the component input properties with
corresponding attributes for the custom element. For example, component
@Input('myInputProp') converted as custom element attribute my-input-prop.
i.
The Component outputs
are dispatched as HTML Custom Events, with the name of the custom event matching
the output name. For example, component @Output() valueChanged = new
EventEmitter() converted as custom element with dispatch event as
"valueChanged".
How
do you define typings for custom elements?
You can use the NgElement and WithProperties types
exported from @angular/elements. Let's see how it can be applied by comparing
with Angular component, The simple container with input property would be as
below,
@Component(...)
class MyContainer {
@Input() message: string;
}
After applying types typescript validates
input value and their types,
const container =
document.createElement('my-container') as NgElement &
WithProperties<{message: string}>;
container.message = 'Welcome to Angular elements!';
container.message = true; // <-- ERROR: TypeScript knows this should
be a string.
container.greet = 'News'; // <-- ERROR: TypeScript knows there is no
`greet` property on `container`.
.What
are dynamic components?
Dynamic components are the components in which
components location in the application is not defined at build time.i.e, They
are not used in any angular template. But the component is instantiated and
placed in the application at runtime.
What
are the various kinds of directives?
There are mainly three kinds of directives.
.
Components —
These are directives with a template.
i.
Structural directives — These directives change the DOM layout by adding and
removing DOM elements.
ii.
Attribute directives — These directives change the appearance or behavior of an
element, component, or another directive.
How
do you create directives using CLI?
You can use CLI command ng generate directive to create the directive class file. It creates the source
file(src/app/components/directivename.directive.ts), the respective test
file(.spec.ts) and declare the directive class file in root module.
Give
an example for attribute directives?
Let's take simple highlighter behavior as a
example directive for DOM element. You can create and apply the attribute
directive using below steps,
.
Create
HighlightDirective class with the file name src/app/highlight.directive.ts. In this file, we need to import Directive from core library to apply the metadata
and ElementRef in
the directive's constructor to inject a reference to the host DOM element ,
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
ii.
Apply the attribute
directive as an attribute to the host element(for example,
)
<p appHighlight>Highlight me!</p>
iii.
Run the application to
see the highlight behavior on paragraph element
ng serve
57. What is Angular Router?
Angular Router is a mechanism in which
navigation happens from one view to the next as users perform application
tasks. It borrows the concepts or model of browser's application navigation.
58. What is the purpose of base href tag?
The routing application should add element to
the index.html as the first child in the tag inorder to indicate how to compose
navigation URLs. If app folder is the application root then you can set the
href value as below
<base href="/">
59. What are the router imports?
The Angular Router which represents a
particular component view for a given URL is not part of Angular Core. It is
available in library named @angular/router to import required router components.
For example, we import them in app module as below,
import { RouterModule, Routes } from '@angular/router';
60. What is router outlet?
The RouterOutlet is a directive from the
router library and it acts as a placeholder that marks the spot in the template
where the router should display the components for that outlet. Router outlet
is used like a component,
<router-outlet></router-outlet>
<!-- Routed components go here -->
61. What are router links?
The RouterLink is a directive on the anchor
tags give the router control over those elements. Since the navigation paths
are fixed, you can assign string values to router-link directive as below,
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
62. What are active router links?
RouterLinkActive is a directive that toggles
css classes for active RouterLink bindings based on the current RouterState.
i.e, the Router will add CSS classes when this link is active and and remove
when the link is inactive. For example, you can add them to RouterLinks as
below
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed todos</a>
</nav>
<router-outlet></router-outlet>
63. What is router state?
RouterState is a tree of activated routes.
Every node in this tree knows about the "consumed" URL segments, the
extracted parameters, and the resolved data. You can access the current
RouterState from anywhere in the application using the Router service and
the routerState property.
@Component({templateUrl:'template.html'})
class MyComponent {
constructor(router: Router) {
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
const id: Observable<string> = child.params.map(p => p.id);
//...
}
}
64. What are router events?
During each navigation, the Router emits
navigation events through the Router.events property allowing you to track the
lifecycle of the route. The sequence of router events is as below,
iii.
NavigationStart,
iv.
RouteConfigLoadStart,
v.
RouteConfigLoadEnd,
vi.
RoutesRecognized,
vii.
GuardsCheckStart,
viii.
ChildActivationStart,
ix.
ActivationStart,
x.
GuardsCheckEnd,
xi.
ResolveStart,
xii.
ResolveEnd,
xiii.
ActivationEnd
xiv.
ChildActivationEnd
xv.
NavigationEnd,
xvi.
NavigationCancel,
xvii.
NavigationError
xviii.
Scroll
67. What
is activated route?
ActivatedRoute contains the information about
a route associated with a component loaded in an outlet. It can also be used to
traverse the router state tree. The ActivatedRoute will be injected as a router
service to access the information. In the below example, you can access route
path and parameters,
@Component({...})
class MyComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map(p => p.id));
const url: Observable<string> = route.url.pipe(map(segments => segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}
68. How
do you define routes?
A router must be configured with a list of
route definitions. You configures the router with routes via the RouterModule.forRoot() method, and adds the result to the AppModule's imports array.
const appRoutes: Routes = [
{ path: 'todo/:id', component: TodoDetailComponent },
{
path: 'todos',
component: TodosListComponent,
data: { title: 'Todos List' }
},
{ path: '',
redirectTo: '/todos',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
69. What
is the purpose of Wildcard route?
If the URL doesn't match any predefined routes
then it causes the router to throw an error and crash the app. In this case,
you can use wildcard route. A wildcard route has a path consisting of two
asterisks to match every URL. For example, you can define PageNotFoundComponent
for wildcard route as below
{ path: '**', component: PageNotFoundComponent }
70. Do
I need a Routing Module always?
No, the Routing Module is a design choice. You
can skip routing Module (for example, AppRoutingModule) when the configuration
is simple and merge the routing configuration directly into the companion
module (for example, AppModule). But it is recommended when the configuration
is complex and includes specialized guard and resolver services.
71. What
is Angular Universal?
Angular Universal is a server-side rendering
module for Angular applications in various scenarios. This is a community-driven project and available under @angular/platform-server package. Recently
Angular Universal is integrated with Angular CLI.
72. What
are different types of compilation in Angular?
Angular offers two ways to compile your
application,
.
Just-in-Time (JIT)
i.
Ahead-of-Time (AOT)
73. What
is JIT?
Just-in-Time (JIT) is a type of compilation
that compiles your app in the browser at runtime. JIT compilation is the
default when you run the ng build (build only) or ng serve (build and serve
locally) CLI commands. i.e, the below commands used for JIT compilation,
ng build
ng serve
74. What
is AOT?
Ahead-of-Time (AOT) is a type of compilation
that compiles your app at build time. For AOT compilation, include the --aot option with the
ng build or ng serve command as below,
ng build --aot
ng serve --aot
Note: The ng build command with the --prod
meta-flag (ng build --prod) compiles with AOT by default.
75. Why
do we need a compilation process?
The Angular components and templates cannot be
understood by the browser directly. Due to that Angular applications require a
compilation process before they can run in a browser. For example, In AOT
compilation, both Angular HTML and TypeScript code converted into efficient
JavaScript code during the build phase before browser runs it.
76. What
are the advantages with AOT?
Below are the list of AOT benefits,
.
Faster rendering: The browser downloads a pre-compiled version of the
application. So it can render the application immediately without compiling the
app.
i.
Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets
within the application javascript which eliminates separate ajax requests.
ii.
Smaller Angular framework download size: Doesn't require downloading the Angular
compiler. Hence it dramatically reduces the application payload.
iii.
Detect template errors earlier: Detects and reports template binding
errors during the build step itself
iv.
Better security: It compiles HTML templates and components into JavaScript.
So there won't be any injection attacks.
77. What
are the ways to control AOT compilation?
You can control your app compilation in two
ways
.
By providing template
compiler options in the tsconfig.json file
i.
By configuring Angular
metadata with decorators
78. What
are the restrictions of metadata?
In Angular, You must write metadata with the
following general constraints,
.
Write expression
syntax with in the supported range of javascript features
i.
The compiler can only
reference symbols which are exported
ii.
Only call the
functions supported by the compiler
iii.
Decorated and
data-bound class members must be public.
79. What
are the two phases of AOT?
The AOT compiler works in three phases,
.
Code Analysis: The compiler records a representation of the source
i.
Code generation: It handles the interpretation as well as places
restrictions on what it interprets.
ii.
Validation: In this phase, the Angular template compiler uses the TypeScript compiler to
validate the binding expressions in templates.
80. Can
I use arrow functions in AOT?
No, Arrow functions or lambda functions can’t
be used to assign values to the decorator properties. For example, the
following snippet is invalid:
@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
To fix this, it has to be changed as following
exported function:
function getService(){
return new MyService();
}
@Component({
providers: [{
provide: MyService, useFactory: getService
}]
})
If you still use arrow function, it generates
an error node in place of the function. When the compiler later interprets this
node, it reports an error to turn the arrow function into an exported
function. Note: From Angular5
onwards, the compiler automatically performs this rewriting while emitting the
.js file.
81. What
is the purpose of metadata JSON files?
The metadata.json file can be treated as a
diagram of the overall structure of a decorator's metadata represented as an
abstract syntax tree(AST). During the analysis phase, the AOT collector scan
the metadata recorded in the Angular decorators and outputs metadata
information in .metadata.json files, one per .d.ts file.
82. Can
I use any javascript feature for expression syntax in AOT?
No, the AOT collector understands a subset of
(or limited) JavaScript features. If an expression uses unsupported syntax, the
collector writes an error node to the .metadata.json file. Later point of time,
the compiler reports an error if it needs that piece of metadata to generate
the application code.
83. What
is folding?
The compiler can only resolve references to
exported symbols in the metadata. Where as some of the non-exported members are
folded while generating the code. i.e Folding is a process in which the
collector evaluate an expression during collection and record the result in the
.metadata.json instead of the original expression. For example, the compiler
couldn't refer selector reference because it is not exported
let selector = 'app-root';
@Component({
selector: selector
})
Will be folded into inline selector
@Component({
selector: 'app-root'
})
Remember that the compiler can’t fold
everything. For example, spread operator on arrays, objects created using new
keywords and function calls.
84. What
are macros?
The AOT compiler supports macros in the form
of functions or static methods that return an expression in a single return expression. For example, let us take a below macro function,
export function wrapInArray<T>(value: T): T[] {
return [value];
}
You can use it inside metadata as an
expression,
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
The compiler treats the macro expression as it
written directly
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
85. Give
an example of a few metadata errors?
Below are some of the errors encountered in
metadata,
.
Expression form not supported: Some of the language features outside of the compiler's
restricted expression syntax used in angular metadata can produce this error.
Let's see some of these examples,
i. 1. export class User { ... }
ii. const prop = typeof User; // typeof is not valid in metadata
2. { provide: 'token', useValue: { [prop]: 'value' } }; // bracket notation is not valid in metadata
iii.
** Reference to a
local (non-exported) symbol:** The compiler encountered a referenced to a
locally defined symbol that either wasn't exported or wasn't initialized. Let's
take an example of this error,
iv. // ERROR
v. let username: string; // neither exported nor initialized
vi.
vii. @Component({
viii.
selector: 'my-component',
ix. template: ... ,
x. providers: [
xi. { provide: User, useValue: username }
xii. ]
xiii.
})
export class MyComponent {}
You
can fix this by either exporting or initializing the value,
export let username: string; // exported
(or)
let username = 'John'; // initialized
xiv.
Function calls are not supported: The compiler does not currently support
function expressions or lambda functions. For example, you cannot set a
provider's useFactory to an anonymous function or arrow function as below.
xv. providers: [
xvi. { provide: MyStrategy, useFactory: function() { ... } },
xvii.
{ provide: OtherStrategy, useFactory: () => { ... } }
]
You
can fix this with exported function
export function myStrategy() { ... }
export function otherStrategy() { ... }
... // metadata
providers: [
{ provide: MyStrategy, useFactory: myStrategy },
{ provide: OtherStrategy, useFactory: otherStrategy },
xviii.
Destructured variable or constant not supported: The compiler does not support references
to variables assigned by destructuring. For example, you cannot write something
like this:
xix. import { user } from './user';
xx.
xxi. // destructured assignment to name and age
xxii.
const {name, age} = user;
xxiii.
... //metadata
xxiv.
providers: [
xxv. {provide: Name, useValue: name},
xxvi.
{provide: Age, useValue: age},
]
You
can fix this by non-destructured values
import { user } from './user';
... //metadata
providers: [
{provide:
Name, useValue: user.name},
{provide:
Age, useValue: user.age},
]
86. What
is metadata rewriting?
Metadata rewriting is the process in which the
compiler converts the expression initializing the fields such as useClass,
useValue, useFactory, and data into an exported variable, which replaces the
expression. Remember that the compiler does this rewriting during the emit of
the .js file but not in definition files( .d.ts file).
87. How
do you provide configuration inheritance?
Angular Compiler supports configuration
inheritance through extends in the tsconfig.json on angularCompilerOptions.
i.e, The configuration from the base file(for example, tsconfig.base.json) are
loaded first, then overridden by those in the inheriting config file.
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
88. How
do you specify angular template compiler options?
The angular template compiler options are
specified as members of the angularCompilerOptions object in the tsconfig.json file. These
options will be specified adjecent to typescript compiler options.
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
89. How
do you enable binding expression validation?
You can enable binding expression validation
explicitly by adding the compiler option fullTemplateTypeCheck in the "angularCompilerOptions"
of the project's tsconfig.json. It produces error messages when a type error is
detected in a template binding expression. For example, consider the following
component:
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
This will produce the following error:
my.component.ts.MyComponent.html(1,1): : Property 'contacts' does not exist on type 'User'. Did you mean 'contact'?
90. What
is the purpose of any typecast function?
You can disable binding expression type
checking using $any() typecast function(by surrounding the expression). In the
following example, the error Property contacts do not exist is suppressed by
casting user to any type.
template: '{{$any(user).contacts.email}}'
The $any() cast function also works with this
to allow access to undeclared members of the component.
template: '{{$any(this).contacts.email}}'
91. What
is a Non-null type assertion operator?
You can use the non-null type assertion
operator to suppress the Object is a possibly 'undefined' error. In the following
example, the user and contact properties are always set together, implying that
contact is always non-null if the user is non-null. The error is suppressed in the
example by using contact!.email.
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}}
contacted through {{contact!.email}} </span>'
})
class MyComponent {
user?: User;
contact?: Contact;
setData(user: User, contact: Contact) {
this.user = user;
this.contact = contact;
}
}
92. What
is type narrowing?
The expression used in a ngIf directive is
used to narrow type unions in the Angular template compiler similar to if the expression in typescript. So *ngIf allows the TypeScript compiler to infer that
the data used in the binding expression will never be undefined.
@Component({
selector: 'my-component',
template: '<span *ngIf="user">
{{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
93. How
do you describe various dependencies in an angular application?
The dependencies section of package.json within an angular application can be divided as follow,
.
Angular packages: Angular core and optional modules; their package names
begin @angular/.
i.
Support packages: Third-party libraries that must be present for Angular
apps to run.
ii.
Polyfill packages: Polyfills plug gaps in a browser's JavaScript
implementation.
94. What
is zone?
A Zone is an execution context that persists
across async tasks. Angular relies on zone.js to run Angular's change detection
processes when native JavaScript operations raise events
95. What
is the purpose of common module?
The commonly-needed services, pipes, and
directives provided by @angular/common module. Apart from these
HttpClientModule is available under @angular/common/http.
96. What is codelyzer ?
Codelyzer provides set of tslint rules for
static code analysis of Angular TypeScript projects. ou can run the static code
analyzer over web apps, NativeScript, Ionic etc. Angular CLI has support for
this and it can be use as below,
ng new codelyzer
ng lint
97. What
is angular animation?
Angular's animation system is built on CSS
functionality in order to animate any property that the browser considers
animatable. These properties includes positions, sizes, transforms, colors,
borders etc. The Angular modules for animations are @angular/animations and @angular/platform-browser and these dependencies are automatically
added to your project when you create a project using Angular CLI.
98. What
are the steps to use animation module?
You need to follow below steps to implement
animation in your angular project,
.
Enabling the animations module: Import BrowserAnimationsModule to add
animation capabilities into your Angular root application module(for example,
src/app/app.module.ts).
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
ii.
Importing animation functions into component files: Import required animation functions from
@angular/animations in component files(for example, src/app/app.component.ts).
import {
trigger,
state,
style,
animate,
transition,
// ...
} from '@angular/animations';
iii.
Adding the animation metadata property: add a metadata property called
animations: within the @Component() decorator in component files(for example,
src/app/app.component.ts)
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
animations: [
// animation triggers go here
]
})
99. What
is State function?
Angular's state() function is used to define
different states to call at the end of each transition. This function takes two
arguments: a unique name like open or closed and a style() function. For
example, you can write a open state function
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
100. What
is Style function?
The style function is used to define a set of
styles to associate with a given state name. You need to use it along with
state() function to set CSS style attributes. For example, in the close state,
the button has a height of 100 pixels, an opacity of 0.8, and a background
color of green.
state('close', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'green'
})),
Note: The style attributes must be in
camelCase
101. What
is the purpose of animate function?
Angular Animations are a powerful way to
implement sophisticated and compelling animations for your Angular single page
web application.
import { Component, OnInit, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-animate',
templateUrl: `<div
[@changeState]="currentState" class="myblock
mx-auto"></div>`,
styleUrls: `.myblock {
background-color: green;
width: 300px;
height:
250px;
border-radius: 5px;
margin: 5rem;
}`,
animations: [
trigger('changeState', [
state('state1', style({
backgroundColor: 'green',
transform: 'scale(1)'
})),
state('state2', style({
backgroundColor: 'red',
transform: 'scale(1.5)'
})),
transition('*=>state1', animate('300ms')),
transition('*=>state2', animate('2000ms'))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState;
constructor() { }
ngOnInit() {
}
}
102. What
is a transition function?
The animation transition function is used to
specify the changes that occur between one state and another over a period of
time. It accepts two arguments: the first argument accepts an expression that
defines the direction between two transition states, and the second argument
accepts an animate() function. Let's take an example state transition from open
to closed with an half second transition between states.
transition('open => closed', [
animate('500ms')
]),
103. How
to inject the dynamic script in angular?
Using DomSanitizer we can inject the dynamic
Html,Style,Script,Url.
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from
'@angular/platform-browser';
@Component({
selector:
'my-app',
template: `
<div
[innerHtml]="htmlSnippet"></div>
`,
})
export class App {
constructor(protected sanitizer: DomSanitizer) {}
htmlSnippet: string =
this.sanitizer.bypassSecurityTrustScript("<script>safeCode()</script>");
}
0 Comments