Planning to make it big as an Angular JS developer? Browse our top Angularjs interview questions and familiarise yourself with the answers prepared by experts.Our Angularjs interview questions will cover topics like types of directives in angular, structural directives in angular, angular component lifecycle methods and nearly everything you need for your next Angular JS interview. Acquaint yourself with the questions commonly asked in Angular JS interviews and be the Angular JS developer companies are looking for.
You create a component in angular with the help of decorator @Component. @Component accepts configuration via an object which is referred to as metadata. A component is responsible for presenting user interface hence we can think of selector and template/templateUrl. Selector property is optional when you use the component in routing. So minimum metadata needed to create a component is template.
The component is responsible to present a user interface, hence it is not possible to create component without a template. If you do so angular throws you an error “No template specified for component MinimumComponent”
You can supply template in 2 ways
Communication between parent and child happens by property binding. Property binding is one way binding offered by angular to assign the value to a property of a component. You can pass any valid javascript value to a property of a component.
Communication between child and parent component happens via event binding using a custom event. You can create custom event property using output decorator (@Output) which of type EventEmitter, a special class provided by angular to power event communication. Child component can then emit an event with event argument as the data to be passed from child to parent. Parent component can listen for the event by binding to this property and accessing the payload through the $event object.
There are three kinds of directives in Angular:
Components are the most used directives and only directive that has a template.
Structural directives as the name say structural directives the ability to alter the structure of the DOM. Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. For example *ngIf, *ngFor, *ngSwitchCase, *ngSwitchDefault
Attribute directives - Used as attributes of elements these directives deal with appearance or behaviour. For example ngStyle and ngClass
*ngIf - used to code conditional rendering inside the template
*ngFor - used to code iterative behaviour inside the template
*ngSwitchCase - use inside switch attribute directive to code matching case
*ngSwitchDefault - use inside switch attribute directive to the code default case
In general, we use property binding to set value for a component/element attribute but if there is not any corresponding property to attribute (for example ‘colspan’) in such cases we use attribute binding. When tried to set colspan on <td> element using interpolation, angular code fails with an error shown below
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
Error:
Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.) and the name of the attribute. You then set the attribute value, using an expression that resolves to a string.
<table border=1> <!-- expression calculates colspan=2, [attr.colspan] is attribute binding --> <tr><td [attr.colspan]="1 + 1">One-Two</td></tr> <!-- ERROR: There is no `colspan` property to set! <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> --> <tr><td>Five</td><td>Six</td></tr> </table>
Class binding allows us to apply or remove css class names dynamically without or without conditions. Class binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix class, optionally followed by a dot (.) and the name of a CSS class: [class.class-name].
Both style binding and ngStyle help us to apply dynamic inline style. However, style binding is good to apply a single style whereas ngStyle will help you to apply multiple dynamic styles.
Style Binding example
<p [style.backgroundColor]="'green'" [style.color]="'white'"> Angular is awesome </p>
ngStyle Binding example
<p [ngStyle]="{backgroundColor:'green',color:'white'}"> Angular is awesome </p>
<button (click)=”toggle()”>click me</button>
In the above template, syntax shows an example of event binding. toggle() method is registered as click handler for the button click event.
@Input decorator is used to make a component property settable. Properties which are decorated with @Input decorator will allow values to flow into the component. Such properties are used in property binding
A variable created within the template and refers to HTML/Angular element. You can create a template reference variable by adding an attribute with #{NAME} for eg. #username on the tag.
<h1 #header>Hello World</h1>,
in this template markup #header is a template reference variable which is referring to HTML element h1
No. You cannot.
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()
formControl - an attribute directive that connects template element with form group control
ng-pristine
ng-dirty
ng-touched
ng-untouched
ng-valid
ng-invalid
No. pipe are presentational utilities and do not altercate any actual values
router-outlet
RouterModule.forRoot - forRoot methods take the routes and creates a module with all the router providers and directives
routerLinkActive - Lets you add a CSS class to an element when the link's route becomes active.
<a routerLink="/blog/1" routerLinkActive="active-link">Angular is awesome</a>
When the url is either '/blog or '/blog/1', the active-link class will be added to the <a> tag.
Yes. Pipes are chainable
Use ** as value for path.
{ path: '**', component: PageNotFoundComponent }
The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.
ActivatedRoute - Angular injects this service instance into the activated component which holds all the metadata about the route. You can read route parameters using ActivatedRoute.snapshot.params property
Selector:[question-list]
Selector property in component metadata accept any valid CSS selector. Above selector [question-list] of type attribute selector. Which means when any html element with question-list attribute will be turned to a container for component. However this is not a good practice as components themselves are containers hence preferred selector would be the named selector.
Angular component styles are scoped to component itself by default. It is a behavior angular simulates to avoid css namespacing issues between components. As components encourages encapsulation hence styles also must be encapsulated. However you can alter this behavior using encapsulation metadata property on component
In the below example you have provided element level css rule inside app.component.css to apply color for h1 element of app component. However app component also uses question-list as child component which as well have h1 element but do not receive color.
Both property binding and interpolation or type of one way binding. Interpolation uses double curly braces is as its syntax to bind value. In interpolation the material that sits between double curly braces is evaluated and result is converted to string value, hence Interpolation does not preserve the type expression value. Due to its loss type nature interpolation is mostly used to provide the text content for the elements. On the other side property binding also do a similar job but preserve the data type. Property binding is a good option when you want to assign value to a component property.
ng generate component question --inline-style --no-spec
Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive. This lifecycle hook fires during the phase of component removal from DOM
Component CSS styles are encapsulated into the component's view and don't affect any other components even the children, this behavior is to solve the CSS scope issues. You can control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata using encapsulation property which takes one of the values from ViewEncapsulation enumeration
ViewEncapsulation.None - No Shadow DOM at all. Hence, no style encapsulation.
ViewEncapsulation.Emulated - No Shadow DOM but simulate the shadow dom style encapsulation.
ViewEncapsulation.Native - Use Shadow v1 DOM to encapsulate styles.
ViewEncapsulation.shadowDom - Use Shadow v2 DOM to encapsulate styles.
There are several ways to add styles to a component:
You can use CSS preprocessors like SASS, LESS and Stylus in the place of default CSS. All you need to do is add them to styleUrls property
Yes. You can use isFirstChange method of SimpleChange instance inside ngOnChanges lifecycle hook. This lifecycle hook executes every time input property changes, look into the below API of SimpleChange class.
ngDoCheck - A callback method that performs change-detection, invoked after the default change-detector runs. The default change-detection algorithm looks for differences by comparing bound-property values by reference across change detection runs. You can use this hook to check for and respond to changes by some other means. I.e., If the model reference doesn’t change, but some property of the Input model changes, you may implement the ngDoCheck lifecycle hook to construct your change detection logic manually.
Every angular template expression needs a context to execute, such context is called as expression context which is generally the component instance to which the template is attached
$event is variable which contains event object. The properties of an $event object vary depending on the type of DOM event. Event binding (awesomeevent) allows to bind to DOM events and to EventEmitter events.
For DOM events $event is the event value of the type of whatever event you listen to. Example MouseEvent, KeyboardEvent etc.,
For EventEmitter events the emitted value is available as $event
EventEmitter class provides the functionality to work with events in angular. You create an instance of this class to create custom events. Use emit method of this class instance to raise an event and use subscribe method to register handlers for those events
Yes, we can pass object method as a value to input property. Any valid javascript data type can be passed as value to input property
You can get reference to template reference variable inside component using @ViewChild decoratort. @ViewChild queries the template for the given template reference and sets the reference to decorated property
Template:
<input type="text" #input/> Component: @ViewChild("input") inputRef: ElementRef;
inputRef is a component property that will be set to reference of HTML element input by @ViewChild. Here @ViewChild is configured to query a template reference variable named input
Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way. Angular elements once packaged can be used like any other HTML element provided by the browser and these can be used in any framework
A configurable property of type array on angular module which tells angular thats configured components in this array will be loaded imperatively(dynamically), which means they are not declaratively used in any template.
Yes. You can use lifecycle method ngOnChanges which will receive SimpleChange instance value which provides information about changes. You can use isFirstChange method on instance received.
ngAfterViewInit - A lifecycle hook that is called after Angular has fully initialized a component's view
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
@Component({ selector: 'async-rand', template: '<div><code>Random </code>: {{ rand | async }}</div>' }) export class AsyncRandComponent { rand = new Observable<number>((observer: Observer<number>) => { setInterval(() => observer.next(Math.random()), 1000); }); }
Use @HostListener to bind a CSS event to host listener. Angular calls the supplied handled method when the host element emits the specified event
@Directive({selector: 'button[counting]'}) class CountClicks { numberOfClicks = 0; @HostListener('click', ['$event.target']) onClick(btn) { console.log('button', btn, 'number of clicks:', this.numberOfClicks++); } } @Component({ selector: 'app', template: '<button counting>Increment</button>', }) class App {}
ActivatedRoute - Angular injects this service instance into the activated component which holds all the metadata about the route. You can read route parameters using ActivatedRoute.snapshot.params property
All HttpClient instance methods returns observables
No. You can declare a component in only ONE module
You create a component in angular with the help of decorator @Component. @Component accepts configuration via an object which is referred to as metadata. A component is responsible for presenting user interface hence we can think of selector and template/templateUrl. Selector property is optional when you use the component in routing. So minimum metadata needed to create a component is template.
The component is responsible to present a user interface, hence it is not possible to create component without a template. If you do so angular throws you an error “No template specified for component MinimumComponent”
You can supply template in 2 ways
Communication between parent and child happens by property binding. Property binding is one way binding offered by angular to assign the value to a property of a component. You can pass any valid javascript value to a property of a component.
Communication between child and parent component happens via event binding using a custom event. You can create custom event property using output decorator (@Output) which of type EventEmitter, a special class provided by angular to power event communication. Child component can then emit an event with event argument as the data to be passed from child to parent. Parent component can listen for the event by binding to this property and accessing the payload through the $event object.
There are three kinds of directives in Angular:
Components are the most used directives and only directive that has a template.
Structural directives as the name say structural directives the ability to alter the structure of the DOM. Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. For example *ngIf, *ngFor, *ngSwitchCase, *ngSwitchDefault
Attribute directives - Used as attributes of elements these directives deal with appearance or behaviour. For example ngStyle and ngClass
*ngIf - used to code conditional rendering inside the template
*ngFor - used to code iterative behaviour inside the template
*ngSwitchCase - use inside switch attribute directive to code matching case
*ngSwitchDefault - use inside switch attribute directive to the code default case
In general, we use property binding to set value for a component/element attribute but if there is not any corresponding property to attribute (for example ‘colspan’) in such cases we use attribute binding. When tried to set colspan on <td> element using interpolation, angular code fails with an error shown below
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
Error:
Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.) and the name of the attribute. You then set the attribute value, using an expression that resolves to a string.
<table border=1> <!-- expression calculates colspan=2, [attr.colspan] is attribute binding --> <tr><td [attr.colspan]="1 + 1">One-Two</td></tr> <!-- ERROR: There is no `colspan` property to set! <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> --> <tr><td>Five</td><td>Six</td></tr> </table>
Class binding allows us to apply or remove css class names dynamically without or without conditions. Class binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix class, optionally followed by a dot (.) and the name of a CSS class: [class.class-name].
Both style binding and ngStyle help us to apply dynamic inline style. However, style binding is good to apply a single style whereas ngStyle will help you to apply multiple dynamic styles.
Style Binding example
<p [style.backgroundColor]="'green'" [style.color]="'white'"> Angular is awesome </p>
ngStyle Binding example
<p [ngStyle]="{backgroundColor:'green',color:'white'}"> Angular is awesome </p>
<button (click)=”toggle()”>click me</button>
In the above template, syntax shows an example of event binding. toggle() method is registered as click handler for the button click event.
@Input decorator is used to make a component property settable. Properties which are decorated with @Input decorator will allow values to flow into the component. Such properties are used in property binding
A variable created within the template and refers to HTML/Angular element. You can create a template reference variable by adding an attribute with #{NAME} for eg. #username on the tag.
<h1 #header>Hello World</h1>,
in this template markup #header is a template reference variable which is referring to HTML element h1
No. You cannot.
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()
formControl - an attribute directive that connects template element with form group control
ng-pristine
ng-dirty
ng-touched
ng-untouched
ng-valid
ng-invalid
No. pipe are presentational utilities and do not altercate any actual values
router-outlet
RouterModule.forRoot - forRoot methods take the routes and creates a module with all the router providers and directives
routerLinkActive - Lets you add a CSS class to an element when the link's route becomes active.
<a routerLink="/blog/1" routerLinkActive="active-link">Angular is awesome</a>
When the url is either '/blog or '/blog/1', the active-link class will be added to the <a> tag.
Yes. Pipes are chainable
Use ** as value for path.
{ path: '**', component: PageNotFoundComponent }
The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.
ActivatedRoute - Angular injects this service instance into the activated component which holds all the metadata about the route. You can read route parameters using ActivatedRoute.snapshot.params property
Selector:[question-list]
Selector property in component metadata accept any valid CSS selector. Above selector [question-list] of type attribute selector. Which means when any html element with question-list attribute will be turned to a container for component. However this is not a good practice as components themselves are containers hence preferred selector would be the named selector.
Angular component styles are scoped to component itself by default. It is a behavior angular simulates to avoid css namespacing issues between components. As components encourages encapsulation hence styles also must be encapsulated. However you can alter this behavior using encapsulation metadata property on component
In the below example you have provided element level css rule inside app.component.css to apply color for h1 element of app component. However app component also uses question-list as child component which as well have h1 element but do not receive color.
Both property binding and interpolation or type of one way binding. Interpolation uses double curly braces is as its syntax to bind value. In interpolation the material that sits between double curly braces is evaluated and result is converted to string value, hence Interpolation does not preserve the type expression value. Due to its loss type nature interpolation is mostly used to provide the text content for the elements. On the other side property binding also do a similar job but preserve the data type. Property binding is a good option when you want to assign value to a component property.
ng generate component question --inline-style --no-spec
Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive. This lifecycle hook fires during the phase of component removal from DOM
Component CSS styles are encapsulated into the component's view and don't affect any other components even the children, this behavior is to solve the CSS scope issues. You can control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata using encapsulation property which takes one of the values from ViewEncapsulation enumeration
ViewEncapsulation.None - No Shadow DOM at all. Hence, no style encapsulation.
ViewEncapsulation.Emulated - No Shadow DOM but simulate the shadow dom style encapsulation.
ViewEncapsulation.Native - Use Shadow v1 DOM to encapsulate styles.
ViewEncapsulation.shadowDom - Use Shadow v2 DOM to encapsulate styles.
There are several ways to add styles to a component:
You can use CSS preprocessors like SASS, LESS and Stylus in the place of default CSS. All you need to do is add them to styleUrls property
Yes. You can use isFirstChange method of SimpleChange instance inside ngOnChanges lifecycle hook. This lifecycle hook executes every time input property changes, look into the below API of SimpleChange class.
ngDoCheck - A callback method that performs change-detection, invoked after the default change-detector runs. The default change-detection algorithm looks for differences by comparing bound-property values by reference across change detection runs. You can use this hook to check for and respond to changes by some other means. I.e., If the model reference doesn’t change, but some property of the Input model changes, you may implement the ngDoCheck lifecycle hook to construct your change detection logic manually.
Every angular template expression needs a context to execute, such context is called as expression context which is generally the component instance to which the template is attached
$event is variable which contains event object. The properties of an $event object vary depending on the type of DOM event. Event binding (awesomeevent) allows to bind to DOM events and to EventEmitter events.
For DOM events $event is the event value of the type of whatever event you listen to. Example MouseEvent, KeyboardEvent etc.,
For EventEmitter events the emitted value is available as $event
EventEmitter class provides the functionality to work with events in angular. You create an instance of this class to create custom events. Use emit method of this class instance to raise an event and use subscribe method to register handlers for those events
Yes, we can pass object method as a value to input property. Any valid javascript data type can be passed as value to input property
You can get reference to template reference variable inside component using @ViewChild decoratort. @ViewChild queries the template for the given template reference and sets the reference to decorated property
Template:
<input type="text" #input/> Component: @ViewChild("input") inputRef: ElementRef;
inputRef is a component property that will be set to reference of HTML element input by @ViewChild. Here @ViewChild is configured to query a template reference variable named input
Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way. Angular elements once packaged can be used like any other HTML element provided by the browser and these can be used in any framework
A configurable property of type array on angular module which tells angular thats configured components in this array will be loaded imperatively(dynamically), which means they are not declaratively used in any template.
Yes. You can use lifecycle method ngOnChanges which will receive SimpleChange instance value which provides information about changes. You can use isFirstChange method on instance received.
ngAfterViewInit - A lifecycle hook that is called after Angular has fully initialized a component's view
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
@Component({ selector: 'async-rand', template: '<div><code>Random </code>: {{ rand | async }}</div>' }) export class AsyncRandComponent { rand = new Observable<number>((observer: Observer<number>) => { setInterval(() => observer.next(Math.random()), 1000); }); }
Use @HostListener to bind a CSS event to host listener. Angular calls the supplied handled method when the host element emits the specified event
@Directive({selector: 'button[counting]'}) class CountClicks { numberOfClicks = 0; @HostListener('click', ['$event.target']) onClick(btn) { console.log('button', btn, 'number of clicks:', this.numberOfClicks++); } } @Component({ selector: 'app', template: '<button counting>Increment</button>', }) class App {}
ActivatedRoute - Angular injects this service instance into the activated component which holds all the metadata about the route. You can read route parameters using ActivatedRoute.snapshot.params property
All HttpClient instance methods returns observables
No. You can declare a component in only ONE module
AngularJS is a modern JavaScript Framework which is used to build highly interactive Single Page Applications. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.
If you are in the web development field or a fresher looking for a future in it then definitely you should learn it. You must have a basic understanding of JavaScript and any text editor. It will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX, etc.
AngularJS developers have an excellent opportunity to intensify their career in AngularJS. In the current market scenario, there are huge opportunities available for web developers. Most of the MNCs companies are looking to hire AngularJS developers for their projects. AngularJS developers gets an average salary of $77,908/yr.
You would agree with the fact that you struggle with tough competition in every interview. Hence, you should prepare yourself well in advance the different Angular Interview Questions. Our Angular Interview Questions have been designed specially to get you familiarized with the nature of the questions you might across in the interview. Angularjs interview questions and answers here will be an added advantage to crack your interview. Angularjs interview questions and answers you have learned so far start with some basic concepts and later continued to advanced level.
We hope these angular interview questions and answers helped you to understand the basic and advanced level of AngularJS. The above angular basic interview questions will definitely enable you to crack your AngularJS interview successfully.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.