Q1. What is Angular 2?
Angular 2 is a completely revived component-based framework in which an application is a tree of loosely coupled components. It is a more advanced version of angularJS. It is more of an “all in one” framework so it also helps in creating a single website without getting trapped into different JS frameworks. An Angular 2 is a modular framework in which our code is divided into individual procedures that offer a similar kind of functionality, hence improving the testing, up gradation and maintenance of the application. It has a lot of useful features such as- server-side rendering, cross-platform, and supports more languages than any other framework. It is a new typescript framework built around the concept of components which is paving the way for a better and spacious development. We can even make hybrid applications using Angular 2 which gives us a sharp edge by providing us the flexibility to use the same standard codes for developing other applications.
Or in nutshell :
AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework.
· Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time.
· TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft.
· Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications.
Q2. List some advantages of Angular 2 over Angular1.
Angular 2 is a re-written version of Angular1 and not an update. The best way to compare Angular 2 and Angular 1 is by finding out the new features in Angular 2. This way we will be able to find out the advantages of Angular 2 over Angular1 precisely. So, some of the advantages of Angular 2 are:-
Angular 2
Angular1
Angular 2 is a mobile-oriented framework
Whereas Angular1 was not developed with mobile base in mind.
Angular 2 is a versatile framework, i.e. we have more choices for languages. We can use ES5, ES6, Typescript or Dart to write an Angular 2 code
Whereas an Angular1 code can written by using only ES5, ES6 and Dart. We don’t have many choices of language in Angular1.
Nowadays, the controllers are replaced by components and Angular 2 is completely component based.
Whereas Angular1 was based on controllers whose scope is now over.
Angular 2 directly uses the valid HTML DOM element properties and events which reduces the usage of many available built-in directives.
Q3. What are the new features of Angular 2?
Angular 2 is a platform that encompasses a wide range of capabilities. Some new features were added in Angular 2 which includes:
<img[src]='product.image' />
Q4. How do you define transition between two states in angular?
Transitions between two states take place so that we can build simple animations between two states driven by a model attribute. Transition basically means navigating from the current state to a new state. In angular, transition is an animation-specific function which is used in angular’s animation DSL language. Transition declares the sequence of animation steps that will be executed when entered value is satisfied. A function is provided an argument for a transition and it will be executed each time a state change occurs. In this, if the function is true, then the animation will run else it won’t get executed.
These animation transitions are placed within the animation triggers. The transition depends upon what the animation was in the previous state and what it will become in the next state. In other words, if a transition is defined that matches the old/current state criteria then the associated animation will be triggered.
Syntax: –
function transition (stateChangeExpr: string, steps: AnimationMetadata | AnimationMetadata []):AnimationTransitionMetadata;
Q5. How to declare a component in Angular 2?
Components in Angular 2 are simply directives that are always associated with a direct template. Angular 2 components have an extremely well defined life-cycle. When working with angular components, we can make use of interfaces which allows us to implement functionality for different times in a components lifecycle. A component must belong to an NgModule in order for it to be usable by another component or application. Components can even control their runtime behaviour by implementing various Life-cycle hooks.
Declaration of component:-
@component ({selector: 'great', template: 'hello {{name}}!'})
Class greet{
Name: string = 'world';
}
Components always have a template and only one component can be instantiated per an element in a template. When a component is instantiated, angular creates a change detector, which is responsible for propagating the component’s building.
Q6. What is the difference between observable and promises?
The differences between observable and promises are:-
A nice answer taken from stack overflow:
A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.
An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event. Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancelable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore. Observable provides operators like map, forEach, reduce, ... similar to an array. There are also powerful operators like retry(), or replay(), ... that are often quite handy.
Promises vs Observables
o Promises:
1. returns a single value
2. not cancellable
o Observables:
1. works with multiple values over time
2. cancellable
3. supports map, filter, reduce and similar operators
4. proposed feature for ES 2016
5. use Reactive Extensions (RxJS)
6. an array whose items arrive asynchronously over time
References/Further Readings:
Q7. List the differences between Angular 2 components vs. directives.
Apart from components, directives are also used in Angular 2 which allows us to attach behavior to elements in DOM. There are certain differences between the components and directives in Angular 2. They are: –
Q8. What is ECMAScript?
ECMAScript is a standard for scripting languages. It is a subset of JavaScript. Languages such as ActionScript, JavaScript use ECMAScript as its core. ECMA stands for European Computer Manufacturer’s Association. Coders commonly use ECMAScript for client-side scripting on the World Wide Web. It is also used for server applications and services. It includes structured, dynamic, functional, and prototype-based features. The ECMAScript was developed by Brendan Eich of Netscape. The ECMAScript is standardized by the ECMA international standards organization in the ECMA-262 and ECMA-402 specifications. It is a programming language which is designed specifically for acting on an existing entity or system. It provides the rules, details, and guidelines that a scripting language must observe to be considered ECMAScript compliant.
Q9. What is Traceur Compiler?
Traceur is a compiler which takes ECMAScript and compiles it down to regular Javascript that runs in your browser. Traceur can be used in several ways like- typing or pasting the ES6 code into the read-eval-print-loop page, or by including traceur in the web page and compiling ES6 code content on the fly, or many other ways. Even traceur is written in ES6, compiled to ES5. The main goal of a traceur compiler is to inform the designs of Javascript features and allows us to write the code in a better manner. Nowadays, traceur compilers are broadly used in Angular 2 platform. It also supports transpilling and type checking via type annotations.
Q10. List the modern browsers supported by Angular 2.
Angular supports most of the recent browsers some of which are-
Q11. When to use Ngoninit and constructor in Angular 2?
Constructors are used for initializing class members and also for dependency injection. Ngonlnit is used for the initialization work. Both of these methods are called when the component is created. It is really important that we should know, when to and how to use them. These are used for providing the best structure for your component’s code. A constructor method is a pre-defined method in the constructor class which is only called when the class is instantiated. It is also used for properly initializing the fields. Constructor in Angular 2 is used to create a new instance of the class. Ngonlnit is the class we import when we implement the constructor in order to use it in a class. The method used in this case is ngOnlnit(). This method helps in initializing the directive or the component after the data bound properties are displayed and the directive or components input are set.
Q12. How to cache an observable data in Angular 2?
Caching of an observable data is done with the help of “observable.cache”. We can use caching in order to cache the response in the memory and then, on the next subscription, instead of requesting the remote server again. This operator is used at the end of the string. Caching is important for the performance, especially on bandwidth restricted devices and slow networks. You should have a good understanding of caching while working with promises but while translating it to observable, it is a bit difficult. Therefore, when interacting with observables, we typically set up a subscription on the consumer side and react to values coming through the pipe. We can easily add caching to the observables by adding publishReplay(1) and refCount.
Q13.List out the differences between ActivatedRoute and RouterState, with reference to Angular 2.
Here are some of the differences between ActivatedRoute and RouterState with reference to Angular 2: –
Q14. What would you have in a shared module in Angular 2?
Shared module is used to import the services in both eager and lazy loaded module. We all know that lazy loaded modules create their own branch on the dependency injection tree. Shared module consists of the services that are registered by the angular in the root app injector. For this, we need not import it in the lazy module because lazy loaded modules already have access to the services defined at the root. Components, pipes and directives are also defined in the shared module. Other modules that import the shared module can use it in their templates. This means that the modules can be imported normally in the lazy loaded module. The shared module contains the code that will be used across the applications and featured modules. It also consists of the common template components. “Dumb components” should also be present in the shared module. It typically consists of some common angular modules too. When you are importing the shared module, you will also need to import the module with its providers, because there is no app module in the test.
Q15. What do you mean by a structural directive in Angular 2?
Structural directives are used to manipulate DOM in angular. Structural directives are responsible for HTML layout. By adding, removing, or manipulating LMNs in angular, they shape or reshape the structure of DOM. This structural directive is applied to a host element with the help of other directives. The directives then do whatever it is supposed to do with that host element and its descendants. Structural directives can be easily recognized. It can also delay the instantiation of a component or an element. It can also be used for cosmetic effect or manually handling the timing of the loading of components. Structural directives are bound to a template. The two most common structural directives are “ngIf” and “ngFor”. The process occurring in a structural directive is dynamic.
Q16. What do you understand by a template variable? How is it used?
A template in Angular 2 is used to instantiate embedded views. A template variable can be accessed in two ways. Either by placing a directive on an element and have the template variable for this embedded view injected into the constructor of the directive using the template variable token, or you can query for the template variable from a component or a directive via query. A template variable in Angular 2 is a reference to a DOM element or directive within a template. Template variables are used to access the values of DOM element properties. It is declared with the help of “#” and “ref-“as prefix. For example: – #myVar and ref-myVar. Template variable names cannot be made duplicate as in this way, it might give unpredictable values. The scope of a reference variable is the entire template. It can be used anywhere inside a template. In Angular 2, a component needs to have a view and to define a view, a template variable is used. It allows us to express data and property binding, event binding and template concerns.
Q17. Explain the concept of lazy loading in Angular 2.
Lazy loading is a module which is used to decrease the start-up time. When lazy is used, then our system application does not need to load everything at once. It only needs to load what the user expects to see when the application first loads. The modules which are lazily loaded will only be loaded when the user navigates to their routes. Lazy loading improves the performance of our system applications. It keeps the initial payload small and these smaller payloads lead to faster download speeds. It helps in lowering the resource cost especially on mobile networks. If a user doesn’t visit a section of the application, they won’t ever download those resources. The concept of lazy loading in angular requires us to format the application in a certain way. All the assets that are to be lazy loaded should be added to its own module. Lazy loading is setup in the main routing file. Lazy loading overcomes the problem of slow loading of applications in their own way which hence improves the loading time of the application.
Lazy loading can be done only in four steps: –
Most of the enterprise application contains various modules for specific business cases. Bundling whole application code and loading will be huge performance impact at initial call. Lazy lading enables us to load only the module user is interacting and keep the rest to be loaded at runtime on demand.
Lazy loading speeds up the application initial load time by splitting the code into multiple bundles and loading them on demand.
Every Angular application must have one main module say AppModule. The code should be splitted into various child modules (NgModule) based on the application business case.
Plunkr Example: Link
1. We don't require to import or declare lazily loading module in root module.
2. Add the route to top level routing (app.routing.ts) and set loadChildren. loadChildren takes absolute path from root folder followed by #{ModuleName}. RouterModule.forRoot() takes routes array and configures the router.
3. Import module specific routing in the child module.
4. In the child module routing, specify path as empty string ' ', the empty path. RouterModule.forChild again takes routes array for the child module components to load and configure router for child.
5. Then, export const routing: ModuleWithProviders
= RouterModule.forChild(routes);
Q18. What is the difference between constructor and ngOnlnit in Angular js?
The comprehensive comparison that taps into components initialization process is given below:-
Q19. What is the meaning of component life cycle in Angular 2?
The component life cycle hooks overview the life cycle sequence and the interfaces. Angular manages the life cycle of a component. Angular creates it, renders it. It can also create and render its children. It also checks when its data bound properties change. It can even destroy it before removing it from the DOM. The life cycle hook offered by angular provides the visibility into these key life moments and the ability to act when they occur. The components go through an entire set of processes or life cycle right from its initiation to the end of the application. There are a number of life cycle hooks which are listed below: –
There are a number of life cycle hooks which are listed below: –
Q20. What is the use of ngForTrackBy directive?
For iterating over a collection in Angular 2, the ngFor directive is used which instantiates a template once per item from the collection. If a data needs to be changed at some point in the collection, then a problem occurs because angular cannot keep a track of items in the collection and has no knowledge of the items which were added or deleted. This results in the deletion of all the DOM elements that are associated with the data and are again created. If the collection is big, then it becomes more complicated because a lot of DOM manipulation occurs which are expensive. So, to solve this problem, a trackBy function is used which takes the index and the current item as arguments and returns the unique identifier for this item.
Q21. List the key components of Angular 2?
The Angular 2 comprises of the following key components:
Q22. What is a template in Angular 2?
The template in Angular 2 is used to define the views of the AngularJS Application.
Q23. How will you convert a string into a percentage?
To convert a string into a percentage format, a percent filter is used.
{{ value_expression | percent [ : digitsInfo [ : locale ] ] }}
value any a number to be formatted as a percentage.
digitsInfo string see DecimalPipe for more details. Optional. Default is undefined.
locale string a string defining the locale to use (uses the current LOCALE_ID by default).Optional. Default is undefined.
Q24. Explain component specific hooks?
Above are few component specific hooks in Angular2.
Q25. What is CLI?
CLI is the acronym of Command Line Interface, which can be used to create the Angular JS application.
Using CLI, you can also create a unit and end-to-end tests for the Angular application.
Q26. What is AOT compilation?
AOT stands for Ahead of Time. It is the compilation in which Angular compiles the components and templates to JavaScript and HTML while developing.
Q27. What are Event emitters?
An Event emitter is a class defined in core module that can be used by components and directives to emit custom events.
Angular 2 doesn’t have bi-directional digest cycle, unlike angular 1. In angular 2, any change occurred in the component always gets propagated from the current component to all its children in hierarchy. If the change from one component needs to be reflected to any of its parent component in hierarchy, we can emit the event by using Event Emitter api.
In short, EventEmitter is class defined in @angular/core module which can be used by components and directives to emit custom events.
@output() somethingChanged = new EventEmitter();
We use somethingChanged.emit(value) method to emit the event. This is usually done in setter when the value is being changed in the class.
This event emit can be subscribed by any component of the module by using subscribe method.
myObj.somethingChanged.subscribe(val) => this.myLocalMethod(val));
Further Reading:
http://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter
https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html
Q28. What is Angular @ RouteParams?
The RouteParams are used to map the given URL’s based on the route URLs and they become optional parameters for that route.
Q29. Explain Angular 2 hidden property?
The hidden property in Angular 2 is a special case.
Q30. Why are decorators used in Angular 2?
In Angular 2, decorators are used as an identifier of class or type of the object that is created by the TypeScript.The Angular 2 identifies the class below decorator call as the definition of the class and extends the decorator specific properties with the class definition.
Q31. Explain host decorator in Angular 2?
The host decorators in Angular 2 bind the properties of components with UI element values. The properties inside a component class definition which are decorated with @HostBinding are accessed in a template from the assigned property that is @HostBinding()title=’Our title'( whatever the title is).
Q32. What are Pipes in Angular 2?
Pipes in Angular 2 are used in templates in order to convert them into a content that is user-friendly and readable one within the interpolation braces that is {{release| date}}, here the symbol “|” denotes the pipe.
Pipes are used in templates to convert output to user friendly and readable form within interpolation braces i.e. {{ release | date }}. The ‘|’ is denoted as pipe.
Q33. How can you handle errors in Angular 2 Applications?
The Angular 2 Applications provide with the option of error handling.
The errors in Angular 2 can be handled by including the ReactJS catch library and later using the catch function.
Q34. Can you automate porting Angular 1 code to Angular 2?
No, currently we are not provided with any such tool that ports the Angular 1 code to the Angular 2 code.
In the process of porting, the Angular 1 code to Angular 2, the side by side manual conversion of Angular 1 directives to the Angular 2 components takes place because they are two different frameworks and hence requires different approaches to solve the same problem.
Routing is a mechanism which enables user to navigate between views/components. Angular 2 simplifies the routing and provide flexibility to configure and define at module level (Lazy loading).
The angular application has single instance of the Router service and whenever URL changes, corresponding Route is matched from the routing configuration array. On successful match, it applies redirects and the router builds a tree of ActivatedRoute objects and contains the current state of the router. Before redirection, the router will check whether new state is permitted by running guards (CanActivate). Route Guards is simply an interface method that router runs to check the route authorization. After guard runs, it will resolve the route data and activate the router state by instantiation the required components into <router-outlet> </router-outlet>
.
Further Reading:
https://www.codeproject.com/Articles/1164813/Angular-Routing
https://vsavkin.com/angular-2-router-d9e30599f9ea#.kt4z1v957
What is the use of codelyzer in angular 2 application.
All enterprise applications follows a set of coding conventions and guidelines to maintain code in better way. Codelyzer is an open source tool to run and check whether the pre-defined coding guidelines has been followed or not. Codelyzer does only static code analysis for angular and typescript project.
Codelyzer runs on top of tslint and its coding conventions are usually defined in tslint.json file. Codelyzer can be run via angular cli or npm directly. Editors like Visual Studio Code and Atom also supports codelyzer just by doing a basic settings.
To set up the codelyzer in Visual Studio code, we can go to File -> Preferences -> User Settings and add the path for tslint rules.
Hide Copy Code
{
"tslint.rulesDirectory": "./node_modules/codelyzer",
"typescript.tsdk": "node_modules/typescript/lib"
}
To run from cli: ng lint.
To run from npm: npm run lint
Further Reading:
https://github.com/mgechev/codelyzer
https://www.youtube.com/watch?v=bci-Z6nURgE
Well, optimization depends on the type and size of application and many other factors. But in general, I would consider the following points while optimizing the angular 2 app:
1. Consider AOT compilation.
2. Make sure the application is bundled, uglified, and tree shaking is done.
3. Make sure the application doesn’t have un-necessary import statements.
4. Make sure that any 3rd party library, which is not used, is removed from the application.
5. Have all dependencies and dev-dependencies are clearly separated.
6. I would consider lazy loading instead of fully bundled app if the app size is more.
Further Reading:
https://www.lucidchart.com/techblog/2016/05/04/angular-2-best-practices-change-detector-performance/
Well, in most of the cases, the 3rd party library comes with its own .d.ts
file for its type definition. In some cases, we need to extend the existing type by providing some more properties to it or if we need to define additional types to avoid Typescript warning.
If we need to extend the type definition for external library, as a good practice, we should not touch the node_modules or existing typings folder. We can create a new folder, say “custom-typings” and keep all customized type definition in that.
To define typings for application (JavaScript/Typescript) objects, we should define interfaces and entity classes in models folder in the respective module of the application.
For those cases, we can define or extend the types by creating our own “.d.ts
” file.
Further Reading:
https://www.typescriptlang.org/docs/handbook/declaration-merging.html
https://typescript.codeplex.com/wikipage?title=Writing%20Definition%20%28.d.ts%29%20Files
http://stackoverflow.com/questions/32948271/extend-interface-defined-in-d-ts-file
Shadow DOM is a part of the HTML spec which allows developers to encapsulate their HTML markup, CSS styles and JavaScript. Shadow DOM, along with a few other technologies, gives developers the ability to build their own 1st class tags, web components and APIs just like the <audio> tag. Collectively, these new tags and APIs are referred to as Web Components. Shadow DOM provides better separation of concern along with lesser conflict of styles and scripts with other HTML DOM elements.
Since shadow DOM are static in nature, it’s a good candidate to be cached as it is not accessible to developer. The cached DOM would be rendered faster in the browser providing better performance. Moreover, shadow DOM can be managed comparatively well while detecting the change in angular 2 application and re-paint of view can be managed efficiently.
References/Further Reading:
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM
https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/
https://code.tutsplus.com/tutorials/intro-to-shadow-dom--net-34966
AOT compilation stands for Ahead Of Time compilation, in which the angular compiler compiles the angular components and templates to native JavaScript and HTML during the build time. The compiled Html and JavaScript is deployed to the web server so that the compilation and render time can be saved by the browser.
Advantages
1. Faster download: Since the app is already compiled, many of the angular compiler related libraries are not required to be bundled, the app bundle size get reduced. So, the app can be downloaded faster.
2. Lesser No. of Http Requests: If the app is not bundled to support lazy loading (or whatever reasons), for each associated html and css, there is a separate request goes to the server. The pre-compiled application in-lines all templates and styles with components, so the number of Http requests to the server would be lesser.
3. Faster Rendering: If the app is not AOT compiled, the compilation process happens in the browser once the application is fully loaded. This has a wait time for all necessary component to be downloaded, and then the time taken by the compiler to compile the app. With AOT compilation, this is optimized.
4. Detect error at build time: Since compilation happens beforehand, many compile time error can be detected, providing a better degree of stability of application.
Disadvantages
1. Works only with HTML and CSS, other file types need a previous build step
2. No watch mode yet, must be done manually (bin/ngc-watch.js) and compiles all the files
3. Need to maintain AOT version of bootstrap file (might not be required while using tools like cli)
4. Needs cleanup step before compiling
References/Further Reading:
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
Explain local reference variables, ViewChild, and ContentChild.
Local template variables in angular2 is used to refer HTML elements and use their properties to access siblings or children.
Let’s consider you have an input field named username.
<input type="text" required ... />
This HTMLInputField can be made available to the template using # symbol with a variable name say username.
<input type="text" #username required ... />
Now, this HTMLInputElement can be accessed from anywhere in the current template for example, checking validation and showing appropriate message based on the validation rule. But, username HTML reference is not accessible in the component/directive.
To access this in the component, angular 2 provides @ViewChild decorator which accepts the local reference variable.
@ViewChild('username') username: HTMLInputElement;
ViewChild element can be read after the view is initialized (ngAfterViewInit).
ContentChild is used to query the reference of the DOM within ng-content. Content Child are set before the ngAfterContentInit lifecycle hook.
For example:
Hide Copy Code
// <code>app.component.ts</code>
<my-component>
<p #contentRef>{{test}}</p>
</ my-component >
// MyComponent.component.ts
@Component({
selector: ‘my-component',
template: `
<ng-content></ng-content>
<div> ContentChild Example </div>
})
export class LifecycleComponent implements ngAfterContentInit{
@ContentChild(‘contentRef’) childContent: HTMLElement;
ngAfterContentInit() {
this.log('ngAfterContentInit');
console.log(this.childContent);
}
}
Further Reading:
What benefits does .ts provide over legacy JS?
TypeScript provides all qualities and functionalities of Javascript; other than this it provides extended qualities such as static type casting which improve code execution efficiency. TS is compiled to Javascript before running on browser, which improve page render time etc.
Why are decorators used in Angular 2?
Decorators are used as identifier of class or type of object that is being created in TypeScript. Angular 2 identifies class below decorator call as definition of class and extend decorator specific properties with class definition.
What is root module for Angular 2 and what are its parameters?
@ngModule is the root module or class for an angular application. It is identified with decorator @ngModule and identifies the entry point of an application. It takes an object as parameter whose properties are imports, exports, declarations, providers, bootstrap.
How does angular 2 keep track of two-way data binding?
Angular 2 runs script for checking model stored values against displayed HTML values once per Javascript event cycle for whole application tree. If any value has changed on either side it replace the value to make them consistent. [(ngModel)]=”foo” is used as two-way binding attribute.
What limits the number of two-way binding attributes in Angular 2?
Too many two-way binding attributes can cause performance concerns in application. Each data binding pushes an event in Javascript event loop messages que, and pushing too many messages can block event loop and browser window.
How is using two-way data binding encouraged in Angular 2?
Using two-way binding within the scope of component only is encouraged. If a model receive too many inputs, its resolution can create inaccuracy.
What is difference between component and directive in Angular 2?
Component is a directive with template. Directive doesn’t have a template, while components have. Directives are identified with @Directive decorator while components are identified as @Component.
How can we bind a variable with DOM element in Angular 2?
Angular 2 provides this feature with ‘#foo’ syntax. A variable resembles Javascript DOM element and can be referenced in controller as well as DOM.
What can be considered as replacement of $watch in Angular 2?
ngOnChanges lifecycle hook can be considered as replacement of $watch in Angular 1. This hook is invoked every time angular identifies a change in components input model with two parameters; currentValue, oldValue.
Can we automate porting Angular 1 code to Angular 2?
No, currently there is no such tool available. Porting Angular 1 code to Angular 2 code will include side by side manual conversion of Angular 1 directives to Angular 2 components because they are two different approaches to solve the same problem and hence two different frameworks.
Which Angular 2 directive can be used for internationalization?
i18n is the Angular 2 directive that is used for internationalization i.e. conversion of static HTML text in multiple languages.
What is Host Decorators in Angular 2?
Host decorators bind properties of component with UI element values. The properties inside component class definition decorated with @HostBinding can be accessed in template from assigned property i.e. @HostBinding() title = ‘My Title’.
What are Observables in Angular2?
Observables in Angular 2 are similar to promises but with major differences that make them better. Observables handle multiple values over time which makes them a good candidate for working with real-time data. Observables can also be cancelled and this gives a better control when working with in-flow of values from a stream. Observables is an ES7 feature which means you need to make use of an external library to use it today. For example, RxJS - https://github.com/Reactive-Extensions/RxJS.
What is a template reference variable, and how would you use it?
A: A variable (defined using a #) in a component template, which can be referenced in other parts of the template. For example, a template variable for a form can then be referenced by other elements of the form.
What are the possible ways to bind component properties to an associated template?
A: Interpolation binding, one way binding, two way binding.
What does the ngFor template syntax look like?
A: example:<ul><li *ngFor="let val of values">{{val}}</li></ul>
What does the pipe syntax look like in Angular templates?
A: example: <div>{{ value | my-pipe : option }}</div>
What does an interpolated string look like in a template?
A: example: <div title="Hello {{username}}">...</div>
What is <ng-container>?
A: A grouping element that does not interfere with styles or layout (it's analogous to curly braces in JavaScript).
What is <ng-template>?
A: It's an Angular element for rendering HTML when using structural directives. The ng-template itself does not render to anything but a commment directly.
Component/Directive Questions
What is the minimum definition of a component?
A: A class with a Component decorator specifying a template.
What is the difference between a component and a template?
A: A component is a directive with a template (representing a view).
What are different kinds of directives supported in Angular 2?
A: Structural, component, and attribute directives.
How do components communicate with each other?
A: Various ways - for example: Input/Output properties, services, ViewChild/ViewContent.
How do you create two way data binding in Angular 2.0?
A: By using the two-way binding syntax [()] (along with ngModel, if you're doing this in the context of a form control element).
How would you create a component to display error messages throughout your application?
A: Implement your own ErrorHandler and configure it in the list of providers for the modules you want it used in.
How would you support logging in your Angular app?
PA: One way would be to use angular2-logger, which is a package inspired by log4j.
How would you use the ngClass directive?
A: For example: <div [ngClass]="{firstCondition: 'class1', secondCondition: 'class2'}">...</div>
How do you resolve a template URL relative to a Component class?
A: By specifying the moduleId to be module.id in the Component decorator. (Note: while this is still needed when using SystemJS, it is not necessary anymore when using Webpack module bundler for Angular 2 projects.)
NgModules Questions:
What is the purpose of NgModule?
A: It's to give Angular information on a particular module’s contents, through decorator properties like: declarations, imports, exports, providers, etc.
How do you decide to create a new NgModule?
A: Typically for a nontrivial feature in an application, that will involve a collection of related components and services.
What are the attributes that you can define in an NgModule annotation?
A: Declarations, imports, exports, providers, bootstrap
What is the difference between a module's forRoot() and forChild() methods and why do you need it?
A: forRoot and forChild are conventional names for methods that deliver different import values to root and feature modules.
What would you have in a shared module?
A: Common components, directives, and pipes used in other modules in your application.
What would you not put shared module?
A: Services that should not have multiple instances created for the application.
What module would you put a singleton service whose instance will be shared throughout the application (e.g. ExceptionService andLoggerService)?
A: Root Module
What is the purpose of exports in an NgModule?
A: Provide components, directives, pipes to other modules for their usage.
Why is it (potentially) bad if SharedModule provides a service to a lazy loaded module?
A: You will have two instances of the service in your application, which is often not what you want.
Can we import a module twice?
A: Yes, and the latest import will be what is used.
Can you re-export classes and modules?
A: Yes.
What kind of classes can you import in an angular module?
A: Components, pipes, directives
What is the use case of services?
A: One very common use case is providing data to components, often by fetching it from a server. Though there’s no real definition of service from Angular point of view – it could do almost anything (e.g., logging is another common use case, among many).
How are the services injected to your application?
A: Via Angular’s DI (Dependency Injection) mechanism
Why is it a bad idea to create a new service in a component like the one below?
let service = new DataService();
A: The object may not be created with its needed dependencies.
How to make sure that a single instance of a service will be used in an entire application?
A: Provide it in the root module.
Why do we need provider aliases? And how do you create one?
A: To substitute an alternative implementation for a provider. Can create like so: { provide: LoggerService, useClass: DateLoggerService }
What is the possible order of lifecycle hooks in Angular?
A: ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy.
When will ngOnInit be called?
A: Called once, after the first ngOnChanges.
How would you make use of onNgInit()?
PA: Fetch initial component data (e.g. from server).
What would you consider a thing you should be careful doing on onNgInit()?
A: You cannot expect the component's children's data-bound properties to have been checked at this point.
What is the difference between onNgInit() and constructor() of a component?
A: A directive’s data-bound input properties are not set until after construction, so that’s one difference.
What is a pure pipe?
A: A pipe that is only executed when Angular detects a pure change to the input value (e.g. new primitive object or new object reference).
What is an impure pipe?
A: A pipe that is executed during every component change detection cycle (i.e., often – every keystroke, mouse move).
What is an async pipe?
A: An impure pipe that accepts a promise or observable as input and eventually returns emitted values.
What kind of data can be used with async pipe?
A: Stateful, asynchronous
What types of pipes are supported in Angular 2?
A: Pure and impure pipes (async pipes a kind of impure pipe).
What is the difference between RouterModule.forRoot() vs RouterModule.forChild()? Why is it important?
A: forRoot is a convention for configuring app-wide Router service with routes, whereas forChild is for configuring the routes of lazy-loaded modules.
How does loadChildren property work?
A: The Router calls it to dynamically load lazy loaded modules for particular routes.
When does a lazy loaded module get loaded?
A: When its related route is first requested.
How would you use a Route Guard?
A: You would implement CanActivate or CanDeactivate and specify that guard class in the route path you’re guarding.
What are some different types of RouteGuards?
A: CanActivate, CanDeactivate, CanLoad, Resolve, etc.
How would you intercept 404 errors in Angular 2?
A: Can provide a final wildcard path like so: { path: ‘**’, component: PageNotFoundComponent }
This link doesn't work. Why? How do I fix it? <div routerLink='product.id'></div>
A: <a [routerLink]=”[’product.id’]”>{{product.id}}</a>
What do route guards return?
A: boolean or a Promise/Observable resolving to boolean value.
What is for?
A: Place where routes are mounted in the app??
How would you select a custom component to style it?
A: Using the :host pseudo-class selector in your component's styles.
How do you reference the host of a component?
A: Let DI inject an ElementRef into the constructor of your component.
What pseudo-class selector targets styles in the element that hosts the component?
A: The :host pseudo class selector.
How would you select all the child components' elements?
A: With the @ViewChildren decorator, like for example:
@ViewChildren(ChildDirective) viewChildren: QueryList<ChildDirective>;
How would you select a css class in any ancestor of the component host element, all the way up to the document root?
A: Using the :host-context() pseudo-class selector.
What selector force a style down through the child component tree into all the child component views?
A: Use the /deep/ selector along with :host pseudo-class selector.
What does :host-context() pseudo-class selector target?
A: The :host-context() selector looks for a CSS class in any ancestor of the component host element, up to the document root.
What does the following css do? :host-context(.theme-light) h2 { background-color: red; }
A: Will change this component’s background-color to red if the context of the host has the .theme-light class applied.
When do you use template driven vs model driven forms? Why?
A: Template driven forms make more sense for simpler forms, at least in terms of validation. Model driven or Reactive forms lend themselves to easier testing of the validation logic, so if that’s complex, Reactive forms make more sense. There’s also the issue of asynchronous (template driven forms) vs. synchronous (model driven).
How do you submit a form?
PA: use the ngSubmit event binding like so: <form (ngSubmit)="onSubmit()" …>
What's the difference between NgForm, FormGroup, and FormControl? How do they work together?
A: FormGroup tracks the value and validity state of a group of AbstractControl instances. FormControl does the same for an individual control. NgForm is a directive that Angular automatically attaches to each <form> tag. It has its own ‘valid’ property which is true only if every contained control is valid.
What's the advantage of using FormBuilder?
A: Reduces repetition and clutter by handling details of control creation for you.
How do you add form validation to a form built with FormBuilder?
A: pass in Validator objects along with the FormControl objects...
What's the difference between dirty, touched, and pristine on a form element?
A: Dirty means it contains user data, touched means the user has at least done something with a particular control (perhaps just literally ‘touched’ it by giving it focus?), and pristine means the control has not been touched at all by the user.
How can you access validation errors in the template to display error messages?
PA: Use formErrors
What is async validation and how is it done?
A: Verifying some field using some asynchronous call (perhaps a server call)… return a Promise<ValidationResult> from your validator. When creating a FormControl object, you can pass an asynchronous validator into the constructor (e.g. new FormControl(‘value’, syncValidator, asyncValidator)).
What is patchValue used for?
A: Setting a form value (one or more fields with an object) bypassing validation.
How do you define transition between two states?
PA: Using the transition and animate function in an animations block like so: animations: [transition('inactive => active'), animate('100 ms ease-in')]
How do you define a wildcare state?
A: Using the asterisk - example: transition('* => active'), animate('100ms ease-in'))
Architecture / Framework Questions:
What are some of the top level building blocks of the Angular framework?
A: Services, Templates, Modules, Components, Providers, etc.
A: Ahead of time compilation.
What are some differences between Angular 2 and 4?
A: Improvements in AOT; allowing else clause in ngIf, few other things...
What are some security related features built in to the Angular framework?
A: Sanitation, to prevent cross site scripting. Built-in support in the HttpClient to prevent cross-site request forgery.
How can you bypass sanitation in Angular and why would you do so?
A: To inject known safe code, you can bypass sanitation (e.g. to embed an iframe).
What is a good use case for ngrx/store?
A: Complex application state management requirements, involving asynchronous requests to update state.
What is Redux and how does it relate to an Angular app?
A: It's a way to manage application state and improve maintainability of asynchronicity in your application by providing a single source of truth for the application state, and a unidirectional flow of data change in the application. ngrx/store is one implementation of Redux principles.
What would be a good use case for having your own routing module?
A: An application whose requirements imply having many routes, and potentially route guards, and child routes.
Where would you configure TypeScript specific compiler options for your project?
A: In the tsconfig.json file.A
What is the tslint.json file used for?
A: Linting the TypeScript code (making sure it conforms to certain standards / conventions).
What does this line do? @HostBinding('[class.valid]') isValid;
A: Applies the css class ‘valid’ to whatever is using this directive conditionally based on the value of isValid.
Why would you use renderer methods instead of using native element methods?
A: Potentially if you’re rendering to something besides the browser, e.g. rendering native elements on a mobile device, or server side rendering (?).
What is the point of calling renderer.invokeElementMethod(rendererEl, methodName)?
A: To invoke a method on a particular element but avoid direct DOM access (so we don’t tie our code just to the browser).
How would you control size of an element on resize of the window in a component?
A: @HostListener('window:resize', ['$event']) onResize(event: any) { this.calculateBodyHeight(); }
What would be a good use for NgZone service?
A: Running an asynchronous process outside of Angular change detection.
How would you protect a component being activated through the router?
A: Route Guards
How would you insert an embedded view from a prepared TemplateRef?
PA: `viewContainerRef.createEmbeddedView(templateRef);
What is Protractor?
A: E2E (end-to-end) testing framework.
What is Karma?
A: Unit test testing library.
What are spec files?
A: Jasmine unit test files.
What is TestBed?
A: Class to create testable component fixtures.
What does detectChanges to in Angular jasmine tests?
A: propagates changes to the DOM by running Angular change detection.
Why would you use a spy in a test?
A: To verify a particular value was returned or a method was called, for example when calling a service.
What is Angular 2?
AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework.
· Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time.
· TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft.
· Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications.
What are the key components of Angular 2?
Angular 2 has the following components −
· Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task.
· Component − This can be used to bring the modules together.
· Templates − This is used to define the views of an Angular JS application.
· Metadata − This can be used to add more data to an Angular JS class.
· Service − This is used to create components which can be shared across the entire application.
Explain Modules in Angular 2.
Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. A module is made up of the following parts −
· Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application.
· Export array − This is used to export components, directives, and pipes which can then be used in other modules.
· Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules.
Explain Components in Angular 2.
Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components.Following is the anatomy of a Component. A component consists of −
· Class − This is like a C or Java class which consists of properties and methods.
· Metadata − This is used to decorate the class and extend the functionality of the class.
· Template − This is used to define the HTML view which is displayed in the application.
What are Angular 2 directives? Explain with examples.
A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module.
· ngIf −
The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code.
*ngIf = 'expression'
If the expression evaluates to true then the corresponding gets added, else the elements are not added.
· ngFor −
The ngFor element is used to elements based on the condition of the For loop.
*ngFor = 'let variable of variablelist'
The variable is a temporary variable to display the values in the variablelist.
How will you handle errors in Angular 2 applications?
Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function.
· The catch function contains a link to the Error Handler function.
· In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue.
· Now, whenever you get an error it will be redirected to the error console of the browser.
What is routing?
Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user.
What is CLI?
Command Line Interface CLICLI can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application.
What is Dependency Injection? Explain with example.
Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection.
Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module.
@Injectable()
export class classname {
}
Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator.
@Component ({
providers : [classname]
})
Explain tsconfig.json file.
This file is used to give the options about TypeScript used for the Angular JS project.
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
Following are some key points to note about the above code.
· The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript.
· The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true.
· The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile.
Explain package.json file.
This file contains information about Angular 2 project. Following are the typical settings in the file.
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation,
supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --killothers --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "<2.4.0",
"@angular/compiler": "<2.4.0",
"@angular/core": "<2.4.0",
"@angular/forms": "<2.4.0",
"@angular/http": "<2.4.0",
"@angular/platform-browser": "<2.4.0",
"@angular/platform-browser-dynamic": "<2.4.0",
"@angular/router": "<3.4.0",
"angular-in-memory-web-api": <0.2.4",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.7.4"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "<2.0.10",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "<2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": <4.0.14",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "2.5.36"
},
"repository": {}
}
Some key points to note about the above code −
· There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application.
· The "build:watch": "tsc -p src/ -w" command is used to compile the typescript in the background by looking for changes in the typescript files.
Explain systemjs.config.json file.
This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code.
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
Some key points to note about the above code −
· 'npm:': 'node_modules/' tells the location in our project where all the npm modules are located.
· The mapping of app: 'app' tells the folder where all our applications files are loaded.
Explain app.module.ts file.
The following code will be present in the app.module.ts file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Let's go through each line of the code in detail.
· The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module.
· The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options.
· The BrowserModule is required by default for any web based angular application.
· The bootstrap option tells Angular which Component to bootstrap in the application.
How will you convert an input to all lowercase?
lowercase filter is used to convert the input to all lowercase.
In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters.
<div>
The name of this Tutorial is {{TutorialName}}
The first Topic is {{appList[0] | lowercase}}
The second Topic is {{appList[1] | lowercase}}
The third Topic is {{appList[2]| lowercase}}
</div>
How will you convert an input to all uppercase?
uppercase filter is used to convert the input to all uppercase.
In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all uppercase letters.
<div>
The name of this Tutorial is {{TutorialName}}
The first Topic is {{appList[0] | uppercase}}
The second Topic is {{appList[1] | uppercase}}
The third Topic is {{appList[2]| uppercase}}
</div>
How will you get a substring from a string?
slice filter is used to slice a piece of data from the input string.
In below example, we've added slice filter to an expression using pipe character. Here property value will be sliced based on the start and end positions.
<div>
The name of this Tutorial is {{TutorialName}}
The first Topic is {{appList[0] | slice:1:2}}
The second Topic is {{appList[1] | slice:1:3}}
The third Topic is {{appList[2]| slice:2:3}}
</div>
How will you convert a string into a date?
date filter is used to convert the input string to date format.
In below example, we've added date filter to an expression using pipe character. Here property value will be converted to date format.
<div>
The date of this Tutorial is {{newdate | date:"MM/dd/yy"}}
</div>
How will you convert a string into a currency?
currency filter is used to convert the input string to currency format.
In below example, we've added currency filter to an expression using pipe character. Here property value will be converted to currency format.
<div>
The currency of this Tutorial is {{newValue | currency}}
</div>
How will you convert a string into a percentage?
percent filter is used to convert the input string to percentage format.
In below example, we've added percent filter to an expression using pipe character. Here property value will be converted to percentage format.
<div>
The percentage of this Tutorial is {{newValue | percent}}
</div>
When ngOnChanges event get called in Angular 2 Application Lifecycle?
When the value of a data bound property changes, then this method is called.
When ngOnInit event get called in Angular 2 Application Lifecycle?
This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
When ngDoCheck event get called in Angular 2 Application Lifecycle?
This is for the detection and to act on changes that Angular can't or won't detect on its own.
When ngAfterContentInit event get called in Angular 2 Application Lifecycle?
This is called in response after Angular projects external content into the component's view.
When ngAfterContentChecked event get called in Angular 2 Application Lifecycle?
This is called in response after Angular checks the content projected into the component.
When ngAfterViewInit event get called in Angular 2 Application Lifecycle?
This is called in response after Angular initializes the component's views and child views.
When ngAfterViewChecked event get called in Angular 2 Application Lifecycle?
This is called in response after Angular checks the component's views and child views.
When ngOnDestroy event get called in Angular 2 Application Lifecycle?
This is the cleanup phase just before Angular destroys the directive/component.