GitHub - Sudheerj-Angular-Interview-questions - List of 300 Angular Interview Questions and Answers
GitHub - Sudheerj-Angular-Interview-questions - List of 300 Angular Interview Questions and Answers
Star Notifications
Code Issues 4
master Go to file
sudheerj … on Oct 1
View code
README.md
Click if you like the project and follow @SudheerJonna for technical
updates.
No. Questions
3 What is TypeScript?
9 What is a template?
10 What is a module?
13 What is metadata?
16 What is a service
24 What is interpolation?
40 What is RxJS?
41 What is subscribing?
42 What is an observable?
43 What is an observer?
45 What is multicasting?
50 What will happen if you do not supply handler for the observer?
What are the mapping rules between Angular component and custom
57
element?
77 What is JIT?
78 What is AOT?
87 What is folding?
98 What is zone?
163 What is the role of template compiler for prevention of XSS attacks?
226 What are the imported modules in CLI generated feature modules?
227 What are the differences between ngmodule and javascript module?
236 What are the different ways to remove duplicate service registration?
246 What are the possible data change scenarios for change detection?
249 Which are the methods of NgZone used to control change detection?
What are the differences between reactive forms and template driven
259
forms?
279
Back to Top
AngularJS Angular
This is based on
It is based on MVC architecture
Service/Controller
Back to Top
3. What is TypeScript?
TypeScript is a strongly typed superset of JavaScript created by Microsoft
that adds optional types, classes, async/await and many other features, and
compiles to plain JavaScript. Angular is written entirely in TypeScript as a
primary language. You can install TypeScript globally as
document.body.innerHTML = greeter(user);
:
The greeter method allows only string type as argument.
Back to Top
Back to Top
Back to Top
:
6. What are directives?
Directives add behaviour to an existing DOM element or an existing
component instance.
Now this directive extends HTML element behavior with a yellow background
as below
Back to Top
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
Back to Top
Component Directive
@View decorator or
Directive doesn't use View
templateurl/template are mandatory
Back to Top
9. What is a template?
:
A template is a HTML view where you can display data by binding controls to
properties of an Angular component. You can store your component's
template in one of two places. You can define it inline using the template
property, or you can define the template in a separate HTML file and link to it
in the component metadata using the @Component decorator's templateUrl
property.
@Component ({
selector: 'my-app',
template: '
<div>
<h1>{{title}}</h1>
<div>Learn Angular</div>
</div>
'
})
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
Back to Top
:
10. What is a module?
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: []
})
export class AppModule { }
Back to Top
Back to Top
<button (click)="logout()"></button>
Back to Top
@Component({
selector: 'my-component',
template: '<div>Class decorator</div>',
})
export class MyComponent {
constructor() {
console.log('Hey I am a component!');
}
}
@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log('Hey I am a module!');
}
}
ii. Property decorators Used for properties inside classes, e.g. @Input
and @Output
@Component({
selector: 'my-component',
template: '<div>Property decorator</div>'
})
@Component({
selector: 'my-component',
template: '<div>Method decorator</div>'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
@Component({
selector: 'my-component',
template: '<div>Parameter decorator</div>'
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}
Back to Top
Below are the list of few commands, which will come handy while creating
angular projects
:
i. Creating New Project: ng new
Back to Top
ngOnInit(){
//called after the constructor and called after the first ngOnChange
//e.g. http call...
}
}
Back to Top
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
Back to Top
:
17. What is dependency injection in Angular?
Back to Top
Module injector
When angular starts, it creates a root injector where the services will be
registered, these are provided via injectable annotation. All services
provided in the ng-model property are called providers (if those modules
are not lazy-loaded).
:
Angular recursively goes through all models which are being used in the
application and creates instances for provided services in the root injector. If
you provide some service in an eagerly-loaded model, the service will be
added to the root injector, which makes it available across the whole
application.
Platform Module
NullInjector()
At the very top, the next parent injector in the hierarchy is the
NullInjector() .The responsibility of this injector is to throw the error if
something tries to find dependencies there, unless you've used
@Optional() because ultimately, everything ends at the NullInjector()
and it returns an error or, in the case of @Optional() , null .
:
ElementInjector
Back to Top
Let's take a time observable which continuously updates the view for every 2
seconds with the current time.
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time: Observable<string>;
constructor() {
this.time = new Observable((observer) => {
setInterval(() => {
observer.next(new Date().toString());
}, 2000);
});
}
}
Back to Top
Back to Top
<p *ngIf="user.age > 18">You are not eligible for student pass!</
Note: Angular isn't showing and hiding the message. It is adding and
removing the paragraph element from the DOM. That improves
performance, especially in the larger projects with many data bindings.
Back to Top
Angular recognizes the value as unsafe and automatically sanitizes it, which
removes the script tag but keeps safe content such as the text content of
the script tag. This way it eliminates the risk of script injection attacks. If
you still use it then it will be ignored and a warning appears in the browser
console.
:
Let's take an example of innerHtml property binding which causes XSS
vulnerability,
Back to Top
<h3>
{{title}}
<img src="{{url}}" style="height:30px">
</h3>
In the example above, Angular evaluates the title and url properties and fills
in the blanks, first displaying a bold application title and then a URL.
Back to Top
Back to Top
i. new
ii. increment and decrement operators, ++ and --
iii. operator assignment, such as += and -=
iv. the bitwise operators | and &
v. the template expression operators
Back to Top
:
27. How do you categorize data binding types?
From the
1. {{expression}} 2. Interpolation,
source-to-
[target]="expression" 3. bind- Property, Attribute,
view(One-
target="expression" Class, Style
way)
From view-to-
1. (target)="statement" 2. on-
source(One- Event
target="statement"
way)
View-to-
source-to- 1. [(target)]="expression" 2.
Two-way
view(Two- bindon-target="expression"
way)
Back to Top
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
:
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
Back to Top
A pipe can accept any number of optional parameters to fine-tune its output.
The parameterized pipe can be created by declaring the pipe name with a
colon ( : ) and then the parameter value. If the pipe accepts multiple
parameters, separate the values with colons. Let's take a birthday example
with a particular format(dd/MM/yyyy):
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'dd/MM/yyyy'}}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Note: The parameter value can be any valid template expression, such as a
string literal or a component property.
Back to Top
@Component({
:
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' | upper
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Back to Top
Apart from built-in pipes, you can write your own custom pipe with the below
key characteristics:
i. A pipe is a class decorated with pipe metadata @Pipe decorator, which
you import from the core Angular library For example,
@Pipe({name: 'myCustomPipe'})
interface PipeTransform {
transform(value: any, ...args: any[]): any
}
iii. The @Pipe decorator allows you to define the pipe name that you'll use
within template expressions. It must be a valid JavaScript identifier.
Back to Top
@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = 'MB'): string {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
Now you can use the above pipe in template expression as below,
template: `
<h2>Find the size of a file</h2>
<p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
`
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
@Injectable()
export class UserProfileService {
constructor(private http: HttpClient) { }
getUserProfile() {
return this.http.get(this.userProfileUrl);
:
return this.http.get(this.userProfileUrl);
}
}
fetchUserProfile() {
this.userProfileService.getUserProfile()
.subscribe((data: User) => this.user = {
id: data['userId'],
name: data['firstName'],
city: data['city']
});
}
Back to Top
getUserResponse(): Observable<HttpResponse<User>> {
return this.http.get<User>(
this.userUrl, { observe: 'response' });
}
Back to Top
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success path
error => this.error = error // error path
);
}
It is always a good idea to give the user some meaningful feedback instead
of displaying the raw error object returned from HttpClient .
Back to Top
For example, you can import observables and operators for using HttpClient
as below,
Back to Top
// Execute with the observer object and Prints out each item
source.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification
Back to Top
Back to Top
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
myObservable.subscribe(myObserver);
Note: If you don't supply a handler for a notification type, the observer
ignores notifications of that type.
Back to Top
Observable Promise
Push errors to
Subscribe method is used for error handling that
the child
facilitates centralized and predictable error handling
promises
Uses only
Provides chaining and subscription to handle
.then()
complex applications
clause
Back to Top
Back to Top
myObservable.subscribe({
next(num) { console.log('Next num: ' + num)},
error(err) { console.log('Received an errror: ' + err)}
});
Back to Top
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')
);
Back to Top
Back to Top
:
49. What are observable creation functions?
Back to Top
50. What will happen if you do not supply handler for the
:
observer?
Usually, 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.
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
@Component(...)
class MyContainer {
@Input() message: string;
}
ii. After applying types typescript validates input value and their types,
Back to Top
Back to Top
Back to Top
Back to Top
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
ng serve
Back to Top
Back to Top
The routing application should add element to the index.html as the first
child in the tag in order 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="/">
Back to Top
Back to Top
<router-outlet></router-outlet>
<!-- Routed components go here -->
Back to Top
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
Back to Top
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of todos
<a routerLink="/completed" routerLinkActive="active">Completed todos
</nav>
<router-outlet></router-outlet>
:
Back to Top
@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);
//...
}
}
Back to Top
i. NavigationStart,
ii. RouteConfigLoadStart,
iii. RouteConfigLoadEnd,
iv. RoutesRecognized,
v. GuardsCheckStart,
vi. ChildActivationStart,
vii. ActivationStart,
viii. GuardsCheckEnd,
:
ix. ResolveStart,
x. ResolveEnd,
xi. ActivationEnd
xii. ChildActivationEnd
xiii. NavigationEnd,
xiv. NavigationCancel,
xv. NavigationError
xvi. Scroll
Back to Top
@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 =
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}
Back to Top
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
ng build
ng serve
Back to Top
Back to Top
Back to Top
Back to Top
In Angular, You must write metadata with the following general constraints,
i. Write expression syntax with in the supported range of javascript
features
ii. The compiler can only reference symbols which are exported
iii. Only call the functions supported by the compiler
iv. Decorated and data-bound class members must be public.
Back to Top
Back to Top
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.
Back to Top
Back to Top
Back to Top
@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.
Back to Top
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
Back to Top
// ERROR
let username: string; // neither exported nor initialized
@Component({
:
@Component({
selector: 'my-component',
template: ... ,
providers: [
{ provide: User, useValue: username }
]
})
export class MyComponent {}
iii. 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.
providers: [
{ provide: MyStrategy, useFactory: function() { ... } },
{ provide: OtherStrategy, useFactory: () => { ... } }
]
Back to Top
Back to Top
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
:
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
Back to Top
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
Back to Top
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
:
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
Back to Top
You can disable binding expression type checking using $any() type cast
function(by surrounding the expression). In the following example, the error
Property contacts does not exist is suppressed by casting user to the 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 }}'
Back to Top
@Component({
:
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}} contacted through {{contact
})
class MyComponent {
user?: User;
contact?: Contact;
Back to Top
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
Back to Top
Back to Top
Back to Top
Back to Top
ng new codelyzer
ng lint
Back to Top
Back to Top
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
import {
trigger,
state,
style,
animate,
transition,
// ...
} from '@angular/animations';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
animations: [
// animation triggers go here
]
})
Back to Top
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
Back to Top
state('close', style({
height: '100px',
opacity: 0.8,
:
backgroundColor: 'green'
})),
Back to Top
@Component({
selector: 'app-animate',
templateUrl: `<div [@changeState]="currentState" class="myblock mx-auto"><
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() {
}
}
Back to Top
Let's take an example state transition from open to closed with an half
second transition between states.
Back to Top
Back to Top
Back to Top
Back to Top
AngularJS Angular
Back to Top
i. You can enable ivy in a new project by using the --enable-ivy flag with
the ng new command
ii. You can add it to an existing project by adding enableIvy option in the
angularCompilerOptions in your project's tsconfig.app.json .
{
"compilerOptions": { ... },
"angularCompilerOptions": {
"enableIvy": true
}
}
Back to Top
Back to Top
{
"projects": {
"my-project": {
"architect": {
"build": {
"options": {
...
"aot": true,
}
}
}
}
}
}
Back to Top
The Angular Language Service is a way to get completions, errors, hints, and
navigation inside your Angular templates whether they are external in an
HTML file or embedded in annotations/decorators in a string. It has the
ability to autodetect that you are opening an Angular file, reads your
tsconfig.json file, finds all the templates you have in your application, and
then provides all the language services.
:
Back to Top
You can install Angular Language Service in your project with the following
npm command,
"plugins": [
{"name": "@angular/language-service"}
]
Note: The completion and diagnostic services works for .ts files only. You
need to use custom plugins for supporting HTML files.
Back to Top
Back to Top
ii. Error checking: It can also warn you of mistakes in your code.
Back to Top
iii. The component app.component.ts file updated with web worker file
Note: You may need to refactor your initial scaffolding web worker code for
sending messages to and from.
Back to Top
You need to remember two important things when using Web Workers in
Angular projects,
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
:
124. What are the case types in Angular?
Back to Top
i. @Component()
ii. @Directive()
iii. @Pipe()
iv. @Injectable()
v. @NgModule()
Back to Top
@Input() myProperty;
@Output() myEvent = new EventEmitter();
Back to Top
Declarable is a class type that you can add to the declarations list of an
NgModule. The class types such as components, directives, and pipes
comes can be declared in the module. The structure of declarations would
be,
declarations: [
YourComponent,
YourPipe,
YourDirective
],
Back to Top
Back to Top
Back to Top
Back to Top
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
subject.next(2);
Back to Top
Back to Top
Back to Top
ng add @angular/bazel
ii. Use in a new application: Install the package and create the application
with collection option
When you use ng build and ng serve commands, Bazel is used behind the
scenes and outputs the results in dist/bin folder.
Back to Top
Back to Top
Back to Top
Back to Top
<input #uname>
and define view child directive and access it in ngAfterViewInit lifecycle hook
@ViewChild('uname') input;
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
:
Back to Top
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
Back to Top
:
140. How do you pass headers for HTTP client?
You can directly pass object map for http client or create HttpHeaders class
to supply the headers.
(or)
let headers = new HttpHeaders().set('header1', headerValue1); // create he
headers = headers.append('header2', headerValue2); // add a new header, cr
headers = headers.append('header3', headerValue3); // add another header
Back to Top
i. The first build contains ES2015 syntax which takes the advantage of
built-in support in modern browsers, ships less polyfills, and results in a
smaller bundle size.
ii. The second build contains old ES5 syntax to support older browsers
with all necessary polyfills. But this results in a larger bundle size.
Note: This strategy is used to support multiple browsers but it only load the
code that the browser needs.
Back to Top
:
142. Is Angular supports dynamic imports?
Yes, Angular 8 supports dynamic imports in router configuration. i.e, You can
use the import statement for lazy loading the module using loadChildren
method and it will be understood by the IDEs(VSCode and WebStorm),
webpack, etc. Previously, you have been written as below to lazily load the
feature module. By mistake, if you have typo in the module name it still
accepts the string and throws an error during build time.
This problem is resolved by using dynamic imports and IDEs are able to find
it during compile time itself.
Back to Top
Back to Top
buildTarget.options.optimization = true;
addBuildTargetOption();
Back to Top
Back to Top
It supports the most recent two versions of all major browsers. The latest
version of Angular material is 8.1.1
Back to Top
@NgModule({
imports: [
// Other NgModule imports...
:
LocationUpgradeModule.config()
]
})
export class AppModule {}
Back to Top
NgUpgrade is a library put together by the Angular team, which you can use
in your applications to mix and match AngularJS and Angular components
and bridge the AngularJS and Angular dependency injection systems.
Back to Top
Note: A chrome browser also opens and displays the test output in the
"Jasmine HTML Reporter".
Back to Top
Back to Top
Back to Top
i. Angular 1:
Angular 1 (AngularJS) is the first angular framework released in the
:
year 2010.
AngularJS is not built for mobile devices.
It is based on controllers with MVC architecture.
ii. Angular 2:
Angular 2 was released in the year 2016. Angular 2 is a complete
rewrite of Angular1 version.
The performance issues that Angular 1 version had has been
addressed in Angular 2 version.
Angular 2 is built from scratch for mobile devices unlike Angular 1
version.
Angular 2 is components based.
iii. Angular 3:
The following are the different package versions in Angular 2:
@angular/core v2.3.0
@angular/compiler v2.3.0
@angular/http v2.3.0
@angular/router v3.3.0
The router package is already versioned 3 so to avoid confusion
switched to Angular 4 version and skipped 3 version.
iv. Angular 4:
The compiler generated code file size in AOT mode is very much
reduced.
With Angular 4 the production bundles size is reduced by hundreds
of KB’s.
Animation features are removed from angular/core and formed as a
separate package.
Supports Typescript 2.1 and 2.2.
Angular Universal
New HttpClient
v. Angular 5:
Angular 5 makes angular faster. It improved the loading time and
execution time.
Shipped with new build optimizer.
Supports Typescript 2.5.
:
Service Worker
vi. Angular 6:
It is released in May 2018.
Includes Angular Command Line Interface (CLI), Component
Development KIT (CDK), Angular Material Package, Angular
Elements.
Service Worker bug fixes.
i18n
Experimental mode for Ivy.
RxJS 6.0
Tree Shaking
vii. Angular 7:
It is released in October 2018.
TypeScript 3.1
RxJS 6.3
New Angular CLI
CLI Prompts capability provide an ability to ask questions to the
user before they run. It is like interactive dialog between the user
and the CLI
With the improved CLI Prompts capability, it helps developers to
make the decision. New ng commands ask users for routing and
CSS styles types(SCSS) and ng add @angular/material asks for
themes and gestures or animations.
viii. Angular 8:
It is released in May 2019.
TypeScript 3.4
ix. Angular 9:
It is released in February 2020.
TypeScript 3.7
Ivy enabled by default
x. Angular 10:
It is released in June 2020.
TypeScript 3.9
TSlib 2.0
:
Back to Top
Back to Top
Back to Top
Back to Top
ng v
:
ng version
ng -v
ng --version
Back to Top
Browser Version
Chrome latest
Firefox latest
IE Mobile 11
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
:
166. What is the purpose of innerHTML?
<div [innerHTML]="htmlSnippet"></div>
Unfortunately this property could cause Cross Site Scripting (XSS) security
bugs when improperly handled.
Back to Top
<p>Interpolated value:</p>
<div >{{htmlSnippet}}</div>
<p>Binding of innerHTML:</p>
<div [innerHTML]="htmlSnippet"></div>
Back to Top
ii. Mark the trusted value by calling some of the below methods
a. bypassSecurityTrustHtml
b. bypassSecurityTrustScript
c. bypassSecurityTrustStyle
d. bypassSecurityTrustUrl
e. bypassSecurityTrustResourceUrl
Back to Top
Back to Top
Back to Top
Back to Top
Angular has built-in support for preventing http level vulnerabilities such as
as cross-site request forgery (CSRF or XSRF) and cross-site script inclusion
(XSSI). Even though these vulnerabilities need to be mitigated on server-
side, Angular provides helpers to make the integration easier on the client
side.
Back to Top
:
173. What are Http Interceptors?
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable
}
You can use interceptors by declaring a service class that implements the
intercept() method of the HttpInterceptor interface.
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable
...
}
}
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true
}
]
...
})
export class AppModule {}
Back to Top
:
174. What are the applications of HTTP interceptors?
i. Authentication
ii. Logging
iii. Caching
iv. Fake backend
v. URL transformation
vi. Modifying headers
Back to Top
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyFirstInterceptor, multi
{ provide: HTTP_INTERCEPTORS, useClass: MySecondInterceptor, multi
],
The interceptors will be called in the order in which they were provided. i.e,
MyFirstInterceptor will be called first in the above interceptors configuration.
Back to Top
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
:
next: HttpHandler
): Observable<HttpEvent<any>> {
}
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi:
],
bootstrap: [AppComponent]
})
export class AppModule {}
Back to Top
Back to Top
For example, let us import German locale and register it in the application
registerLocaleData(localeDe, 'de');
Back to Top
ii. Create a translation file: Use the Angular CLI xi18n command to extract
the marked text into an industry-standard translation source file. i.e,
Open terminal window at the root of the app project and run the CLI
command xi18n.
ng xi18n
:
The above command creates a file named messages.xlf in your
project's root directory.
Note: You can supply command options to change the format, the
name, the location, and the source locale of the extracted file.
iii. Edit the generated translation file: Translate the extracted text into the
target language. In this step, create a localization folder (such as
locale )under root directory(src) and then create target language
translation file by copying and renaming the default messages.xlf file.
You need to copy source text node and provide the translation under
target tag. For example, create the translation file(messages.de.xlf) for
German language
iv. Merge the completed translation file into the app: You need to use
Angular CLI build command to compile the app, choosing a locale-
specific configuration, or specifying the following command options.
Back to Top
Back to Top
:
181. What is the purpose of custom id?
When you change the translatable text, the Angular extractor tool generates
a new id for that translation unit. Because of this behavior, you must then
update the translation file with the new id every time.
Back to Top
You need to define custom ids as unique. If you use the same id for two
different text messages then only the first one is extracted. But its
translation is used in place of both original text messages.
For example, let's define same custom id myCustomId for two messages,
and the translation unit generated for first text in for German language as
<h2>Guten Morgen</h2>
<h2>Guten Morgen</h2>
Back to Top
Back to Top
By the way, you can also assign meaning, description and id with the i18n-
x="|@@" syntax.
Back to Top
Back to Top
ICU expression is is similar to the plural expressions except that you choose
among alternative translations based on a string value instead of a number.
Here you define those string values.
Back to Top
i. Error: It throws an error. If you are using AOT compilation, the build will
fail. But if you are using JIT compilation, the app will fail to load.
ii. Warning (default): It shows a 'Missing translation' warning in the
console or shell.
iii. Ignore: It doesn't do anything.
:
If you use AOT compiler then you need to perform changes in
configurations section of your Angular CLI configuration file, angular.json.
"configurations": {
...
"de": {
...
"i18nMissingTranslation": "error"
}
}
If you use the JIT compiler, specify the warning level in the compiler config
at bootstrap by adding the 'MissingTranslationStrategy' property as below,
platformBrowserDynamic().bootstrapModule(AppModule, {
missingTranslation: MissingTranslationStrategy.Error,
providers: [
// ...
]
});
Back to Top
You can provide build configuration such as translation file path, name,
format and application url in configuration settings of Angular.json file.
For example, the German version of your application configured the build as
follows,
"configurations": {
"de": {
"aot": true,
"outputPath": "dist/my-project-de/",
"baseHref": "/fr/",
:
"i18nFile": "src/locale/messages.de.xlf",
"i18nFormat": "xlf",
"i18nLocale": "de",
"i18nMissingTranslation": "error",
}
Back to Top
Note: You can create own third party library and publish it as npm package
to be used in an Application.
Back to Top
Back to Top
You can control any DOM element via ElementRef by injecting it into your
component's constructor. i.e, The component should have constructor with
ElementRef parameter,
constructor(myElement: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
:
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
ii. Add the jquery script: In Angular-CLI project, add the relative path to
jquery in the angular.json file.
"scripts": [
"node_modules/jquery/dist/jquery.min.js"
]
iii. Start using jquery: Define the element in template. Whereas declare
the jquery variable and apply CSS classes on the element.
<div id="elementId">
<h1>JQuery integration</h1>
</div>
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit(): void {
$(document).ready(() => {
$('#elementId').css({'text-color': 'blue', 'font-size':
});
}
}
Back to Top
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Back to Top
You can access the current RouterState from anywhere in the Angular app
using the Router service and the routerState property.
Back to Top
But if you are changing your existing style in your project then use ng set
command,
Back to Top
<div [hidden]="!user.name">
My name is: {{user.name}}
</div>
Back to Top
:
201. What is the difference between ngIf and hidden property?
The main difference is that *ngIf will remove the element from the DOM,
while [hidden] actually plays with the CSS style by setting display:none .
Generally it is expensive to add and remove stuff from the DOM for frequent
actions.
Back to Top
For example, you can provide 'hello' list based on a greeting array,
@Component({
selector: 'list-pipe',
template: `<ul>
<li *ngFor="let i of greeting | slice:0:5">{{i}}</li>
</ul>`
})
export class PipeListComponent {
greeting: string[] = ['h', 'e', 'l', 'l', 'o', 'm','o', 'r', 'n'
}
Back to Top
For example, you can capture the index in a variable named indexVar and
displays it with the todo's name using ngFor directive as below.
:
<div *ngFor="let todo of todos; let i=index">{{i + 1}} - {{todo.name
Back to Top
Back to Top
For example, let's display the browser details based on selected browser
using ngSwitch directive.
:
<div [ngSwitch]="currentBrowser.name">
<chrome-browser *ngSwitchCase="'chrome'" [item]="currentBrowser"
<firefox-browser *ngSwitchCase="'firefox'" [item]="currentBrowser"
<opera-browser *ngSwitchCase="'opera'" [item]="currentBrowser"
<safari-browser *ngSwitchCase="'safari'" [item]="currentBrowser"
<ie-browser *ngSwitchDefault [item]="currentItem"></
</div>
Back to Top
Back to Top
Using this safe navigation operator, Angular framework stops evaluating the
expression when it hits the first null value and renders the view without any
errors.
Back to Top
Back to Top
Back to Top
Back to Top
i. Pipe operator
ii. Safe navigation operator
iii. Non-null assertion operator
Back to Top
Back to Top
Basically, there are two main kinds of entry components which are following
-
:
i. The bootstrapped root component
ii. A component you specify in a route
Back to Top
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent] // bootstrapped entry component need to be dec
})
Back to Top
interface DoBootstrap {
ngDoBootstrap(appRef: ApplicationRef): void
}
:
The module needs to be implement the above interface to use the hook for
bootstrapping.
Back to Top
Back to Top
Since router definition requires you to add the component in two places
(router and entryComponents), these components are always entry
components.
Note: The compilers are smart enough to recognize a router definition and
automatically add the router component into entryComponents .
:
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
:
222. What is the role of ngModule metadata in compilation
process?
The @NgModule metadata is used to tell the Angular compiler what
components to be compiled for this module and how to link this module with
other modules.
Back to Top
Back to Top
Back to Top
Feature modules are NgModules, which are used for the purpose of
organizing code. The feature module can be created with Angular CLI using
the below command in the root directory,
@NgModule({
imports: [
CommonModule
],
declarations: []
})
export class MyCustomFeature { }
Note: The "Module" suffix shouldn't present in the name because the CLI
appends it.
Back to Top
Back to Top
There is no restriction
NgModule bounds declarable classes only
:
classes
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
@Injectable({
providedIn: SomeModule,
})
export class SomeService {
}
@NgModule({
providers: [SomeService],
})
export class SomeModule {
:
export class SomeModule {
}
Back to Top
@Injectable({
providedIn: 'root',
})
export class MyService {
}
ii. Include the service in root module or in a module that is only imported
by root module. It has been used to register services before Angular 6.0.
@NgModule({
...
providers: [MyService],
...
})
Back to Top
Back to Top
Back to Top
The Shared Module is the module in which you put commonly used
directives, pipes, and components into one module that is shared(import it)
throughout the application.
@NgModule({
imports: [ CommonModule ],
declarations: [ UserComponent, NewUserDirective, OrdersPipe ],
exports: [ UserComponent, NewUserDirective, OrdersPipe,
:
CommonModule, FormsModule ]
})
export class SharedModule { }
Back to Top
Back to Top
In Angular 9.1, the API method getLocaleDirection can be used to get the
current direction in your app. This method is useful to support Right to Left
locales for your Internationalization based applications.
...
constructor(@Inject(LOCALE_ID) locale) {
Back to Top
"scripts": {
"postinstall": "ngcc"
}
Back to Top
Back to Top
Back to Top
/*********************************************************************
* Zone JS is required by default for Angular itself.
*/
// import 'zone.js/dist/zone'; // Included with Angular CLI.
platformBrowserDynamic().bootstrapModule(AppModule, {ngZone:
.catch(err => console.error(err));
Back to Top
Back to Top
246. What are the possible data update scenarios for change
detection?
:
The change detection works in the following scenarios where the data
changes needs to update the application HTML.
@Component({
selector: 'app-event-listener',
template: `
<button (click)="onClick()">Click</button>
{{message}}`
})
export class EventListenerComponent {
message = '';
onClick() {
this.message = 'data updated';
}
}
iii. HTTP Data Request: You can get data from a server through an HTTP
request
ngOnInit() {
this.httpClient.get(this.serverUrl).subscribe(response =>
this.data = response.data; // change detection will happen autom
});
}
iv. Macro tasks setTimeout() or setInterval(): You can update the data in
the callback function of setTimeout or setInterval
ngOnInit() {
setTimeout(() => {
:
this.data = 'data updated'; // Change detection will happen auto
});
}
v. Micro tasks Promises: You can update the data in the callback function
of promise
ngOnInit() {
Promise.resolve(1).then(v => {
this.data = v; // Change detection will happen automatically
});
}
vi. Async operations like Web sockets and Canvas: The data can be
updated asynchronously using WebSocket.onmessage() and
Canvas.toBlob().
Back to Top
zone.run(() => {
// outside zone
expect(zoneThis).toBe(zone);
setTimeout(function() {
// the same outside zone exist here
expect(zoneThis).toBe(zone);
});
});
iii. onHasTask: This hook triggers when the status of one kind of task
inside a zone changes from stable(no tasks in the zone) to unstable(a
new task is scheduled in the zone) or from unstable to stable.
Back to Top
:
249. What are the methods of NgZone used to control change
detection?
NgZone service provides a run() method that allows you to execute a
function inside the angular zone. This function is used to execute third party
APIs which are not handled by Zone and trigger change detection
automatically at the correct time.
Back to Top
/*************************************************************************
* Zone JS is required by default for Angular.
*/
import `./zone-flags`;
import 'zone.js/dist/zone'; // Included with Angular CLI.
Back to Top
content_copy
@Component({
selector: 'app-up-down',
animations: [
trigger('upDown', [
state('up', style({
height: '200px',
opacity: 1,
:
opacity: 1,
backgroundColor: 'yellow'
})),
state('down', style({
height: '100px',
opacity: 0.5,
backgroundColor: 'green'
})),
transition('up => down', [
animate('1s')
]),
transition('down => up', [
animate('0.5s')
]),
]),
],
templateUrl: 'up-down.component.html',
styleUrls: ['up-down.component.css']
})
export class UpDownComponent {
isUp = true;
toggle() {
this.isUp = !this.isUp;
}
Back to Top
Back to Top
ii. The below AppService with dummy decorator and httpService can be
injected in AppComponent without any problems. This is because meta
information is generated with dummy decorator.
function SomeDummyDecorator() {
return (constructor: Function) => console.log(constructor);
}
@SomeDummyDecorator()
export class AppService {
constructor(http: HttpService) {
console.log(http);
}
}
:
and the generated javascript code of above service has meta information
about HttpService, js var AppService = (function () { function
AppService(http) { console.log(http); } AppService = __decorate([
core_1.Injectable(), __metadata('design:paramtypes',
[http_service_1.HttpService]) ], AppService); return AppService; }
()); exports.AppService = AppService; 3. The below AppService with
@injectable decorator and httpService can be injected in AppComponent
without any problems. This is because meta information is generated with
Injectable decorator. js @Injectable({ providedIn: 'root', }) export
class AppService { constructor(http: HttpService) {
console.log(http); } } Back to Top
Back to Top
Back to Top
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
@Component({
selector: 'user-profile',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userName = new FormControl('');
}
<label>
User name:
<input type="text" [formControl]="userName">
:
<input type="text" [formControl]="userName">
</label>
@Component({
selector: 'user-profile',
styleUrls: ['./user-profile.component.css'],
template: `
<label>
User name:
<input type="text" [formControl]="userName">
</label>
`
})
export class UserProfileComponent {
userName = new FormControl('');
}
Back to Top
ii. Bind the form from template to the component using ngModel syntax
<form #registerForm="ngForm">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Please enter your name
</div>
v. Let's submit the form with ngSubmit directive and add type="submit"
button at the bottom of the form to trigger form submit.
:
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
// Form goes here
<button type="submit" class="btn btn-success" [disabled]="!registerFor
<div class="container">
<h1>Registration Form</h1>
<form (ngSubmit)="onSubmit()" #registerForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Please enter your name
</div>
</div>
<button type="submit" class="btn btn-success" [disabled]="!registerFor
</form>
</div>
Back to Top
Form
Created(FormControl instance)
model Created by directives
in component explicitly
setup
Data
Synchronous Asynchronous
updates
:
updates
Form
custom Defined as Functions Defined as Directives
validation
Back to Top
@Component({
selector: 'user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userProfile = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
:
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
onSubmit() {
// Store this.userProfile.value in DB
}
}
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
:
</label>
</div>
<button type="submit" [disabled]="!userProfile.valid">Submit
</form>
ii. FormArray: It defines a dynamic form in an array format, where you can
add and remove controls at run time. This is useful for dynamic forms
when you don’t know how many controls will be present within the
group.
@Component({
selector: 'order-form',
templateUrl: './order-form.component.html',
styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent {
constructor () {
this.orderForm = new FormGroup({
firstName: new FormControl('John', Validators.minLength
lastName: new FormControl('Rodson'),
items: new FormArray([
new FormControl(null)
])
});
}
onSubmitForm () {
// Save the items this.orderForm.value in DB
}
onAddItem () {
this.orderForm.controls
.items.push(new FormControl(null));
}
onRemoveItem (index) {
this.orderForm.controls['items'].removeAt(index);
}
}
:
<form [formControlName]="orderForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div>
<p>Add items</p>
<ul formArrayName="items">
<li *ngFor="let item of orderForm.controls.items.controls; let i =
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Item" (click)="onRemoveItem(
</li>
</ul>
<button type="button" (click)="onAddItem">
Add an item
</button>
</div>
Back to Top
updateProfile() {
this.userProfile.patchValue({
firstName: 'John',
address: {
street: '98 Crescent Street'
}
});
}
:
<button (click)="updateProfile()">Update Profile</button>
Note: Remember to update the properties against the exact model structure.
Back to Top
For example, the user profile component creation becomes easier as shown
here.
Back to Top
{{diagnostic}}
<div class="form-group">
// FormControls goes here
</div>
Back to Top
Back to Top
In a model-driven form, you can reset the form just by calling the function
reset() on our form model. For example, you can reset the form model on
submission as follows,
onSubmit() {
if (this.myform.valid) {
:
if (this.myform.valid) {
console.log("Form is submitted");
// Perform business logic here
this.myform.reset();
}
}
Now, your form model resets the form back to its original pristine state.
Back to Top
this.myForm = formBuilder.group({
firstName: ['value'],
lastName: ['value', *Some Sync validation function*],
email: ['value', *Some validation function*, *Some asynchronous
});
Back to Top
Back to Top
Since all validators run after every form value change, it creates a major
impact on performance with async validators by hitting the external API on
each keystroke. This situation can be avoided by delaying the form validity
by changing the updateOn property from change (default) to submit or blur.
The usage would be different based on form types,
Back to Top
In this case, You need to use either ng-container or ng-template. Let's say if
you try to loop over the items only when the items are available, the below
code throws an error in the browser
<ng-container *ngIf="items">
<ul *ngFor="let item of items">
<li></li>
</ul>
</ng-container>
Back to Top
Back to Top
:
271. How do you get the current route?
console.log(this.router.url); // /routename
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
i. component-name.component.ts
ii. component-name.component.css
iii. component-name.component.spec
iv. component-name.component.html
Back to Top
@Component({
standalone: true,
imports: [CommonModule],
selector: 'app-standalone-component',
templateUrl: './standalone-component.component.html',
styleUrls: ['./standalone-component.component.css'],
})
export class ComponentNameComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
@NgModule({
:
imports: [
BrowserModule,
ComponentNameComponent
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Back to Top
import {
bootstrapApplication,
provideClientHydration,
} from '@angular/platform-browser';
bootstrapApplication(RootCmp, {
providers: [provideClientHydration()]
});
@NgModule({
declarations: [RootCmp],
exports: [RootCmp],
:
bootstrap: [RootCmp],
providers: [provideClientHydration()],
})
export class AppModule {}
Back to Top
Releases
No releases published
Packages
No packages published
Contributors 25
+ 14 contributors
: