Angular Interview Question and Answer
Angular Interview Question and Answer
AngularJS Angular
This uses use JavaScript to build the application Introduced the typescript to write the application
Difficulty in SEO friendly application development Ease to create SEO friendly applications
3. What is TypeScript?
TypeScript is a typed superset of JavaScript created by Microsoft that adds
optional types, classes, async/await, and many other features, and compiles to
plain JavaScript. Angular built entirely in TypeScript and used as a primary
language. You can install it globally as
document.body.innerHTML = greeter(user);
Now this directive extends HTML element behavior with a yellow background as
below
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
Component Directive
Component is used to break up the application into Directive is use to design re-usable
smaller components components
Only one component can be present per DOM Many directives can be used per DOM
element element
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. Using inline
template with template syntax,
@Component ({
selector: 'my-app',
template: '
<div>
<h1>{{title}}</h1>
<div>Learn Angular</div>
</div>
'
})
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
i. From the Component to the DOM: Interpolation: {{ value }}: Adds the
value of a property from the component
<button (click)="logout()"></button>
@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>'
})
iii. Method decorators Used for methods inside classes, e.g. @HostListener
@Component({
selector: 'my-component',
template: '<div>Method decorator</div>'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
iv. Parameter decorators Used for parameters inside class constructors, e.g.
@Inject
Below are the list of few commands, which will come handy while creating
angular projects
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
3. What is a service?
A service is used when a common functionality needs to be provided to various
modules. Services allow for greater separation of concerns for your application
and better modularity by allowing you to extract common functionality out of
components. Let's create a repoService which can be used across components,
fetchAll(){
return this.http.get('https://api.github.com/repositories').map(res =>
res.json());
}
}
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
<p *ngIf="user.age > 18">You are not eligible for student pass!</p>
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.
<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.
. new
i. increment and decrement operators, ++ and --
ii. operator assignment, such as += and -=
iii. the bitwise operators | and &
iv. the template expression operators
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
16. What is a parameterized pipe?
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>` //
18/06/1987
})
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.
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' |
uppercase}} </p>` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
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.
@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>
`
/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@Injectable()
export class UserProfileService {
constructor(private http: HttpClient) { }
}
getUserProfile() {
return this.http.get(this.userProfileUrl);
}
iii. Create a component for subscribing service: Let's create a component
called UserProfileComponent(userprofile.component.ts) which inject
UserProfileService and invokes the service method,
fetchUserProfile() {
this.userProfileService.getUserProfile()
.subscribe((data: User) => this.user = {
id: data['userId'],
name: data['firstName'],
city: data['city']
});
}
getUserResponse(): Observable<HttpResponse<User>> {
return this.http.get<User>(
this.userUrl, { observe: 'response' });
}
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.
// Execute with the observer object and Prints out each item
myObservable.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
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.
31. What is the difference between promise and
observable?
Below are the list of differences between promise and observable,
Observable Promise
Declarative: Computation does not start until subscription so that they can be Execute immediately on
run whenever you need the result creation
Subscribe method is used for error handling which makes centralized and Push errors to the child
predictable error handling promises
Provides chaining and subscription to handle complex applications Uses only .then() clause
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')
);
After applying types typescript validates input value and their types,
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
iii. Run the application to see the highlight behavior on paragraph element
ng serve
<base href="/">
65. 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';
<router-outlet></router-outlet>
<!-- Routed components go here -->
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
<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>
69. 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);
//...
}
}
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
71. 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));
}
}
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
73. 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
. Just-in-Time (JIT)
i. Ahead-of-Time (AOT)
ng build
ng serve
78. 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.
@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
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.
Remember that the compiler can’t fold everything. For example, spread operator
on arrays, objects created using new keywords and function calls.
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
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: () => { ... } }
]
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
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}}'
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}} contacted through
{{contact!.email}} </span>'
})
class MyComponent {
user?: User;
contact?: Contact;
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
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
]
})
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
104. 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'
})),
@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() {
}
}