Web / Angular Interview questions
AngularJS is a javascript framework used for creating single web page applications and dynamic web apps.
AngularJS is a structural framework that lets you use HTML as your template language and enables you extend HTML syntax to express your application components clearly and succinctly.
- Two Way Data-Binding,
- Templates,
- MVC,
- Dependency Injection,
- Directives,
- Testing.
- AngularJS is a powerful JavaScript based framework that enables creating Single Page Application (SPA) and RICH Internet Application(RIA).
- AngularJS applications are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
- AngularJS is open source, free and used by many developers around the world. It is licensed under the Apache License version 2.0. https://www.madewithangular.com has the list of popular applications built with AngularJS.
-
AngularJS enables developers to write client side Javascript application using MVC (Model View Controller) pattern.
Using AngularJS developers write less code and achieve more functionality.
- AngularJS applications are unit testable.
- AngularJS provides two-way data binding capability to HTML thus facilitating the users a rich and responsive experience.
- AngularJS uses dependency injection and make use of separation of concerns. AngularJS helps creating reusable components.
The below 3 core directives forms the AngularJS framework.
- ng-app − directive defines and links an AngularJS application to HTML.
- ng-model − directive binds the AngularJS application data to HTML input controls.
- ng-bind − binds the AngularJS Application data to HTML tags.
- AngularJS runs on the client side browser that make it quite obvious to compromise on the Application security. By minimizing the JS files in Production environment and leveraging other security measures, we could build better application security.
- Client must enable JavaScript in the browser to run the AngularJS applications. Otherwise, the user will just see a blank page.
- Memory leak in JavaScript can cause slow down of any browser. AngularJS works well only from Internet Explorer 8.0 onwards and doesn't support any older versions.
AngularJS expressions are code snippets that are usually placed in binding inside double braces such as {{ expression }}.
Expressions are used to bind application data to html. AngularJS expressions are pure javascript expressions and outputs the data where they are used.
Yes. Using ng-init directive and a simple init function we can pass parameters to the AngularJS Controller.
Bower is a package manager for the web, Bower can manage AngularJS components that contain HTML, CSS, JavaScript, fonts or even image files.
Bower does not concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies.
Angular applications are made up of components. A component is the combination of an HTML template and a component class that controls a portion of the screen.
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hello {{name}}</h1>` }) export class AppComponent { name = 'javapedia.net'; }
A component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.
They are TypeScript files, a superset of JavaScript. Angular uses TypeScript because its types make it easy to support developer productivity with tooling.
The below are the ways to communicate between modules of your application using core AngularJS functionality include,
- Using services,
- Using events,
- By assigning models on $rootScope,
- Directly between controllers, using $parent, $$childHead, $$nextSibling.
- Directly between controllers, using ControllerAs, or other forms of inheritance.
It relies on $interpolation, a service called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a watch() is set. $interpolation returns a function, which has a single argument, "context". By calling that function and providing a scope as context, the expressions are $parse()-ed against that scope.
$rootScope is the parent object of all $scope objected created in an angular application.
- Simpler configuration than plain directives.
- Promote sane defaults and best practices.
- Optimized for component-based architecture.
- Writing component directives will make it easier to upgrade to Angular 2.
The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.
ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively.
'then' template is the inline template of ngIf unless bound to a different value and 'else' template is blank unless it is bound.
ng-show/ng-hide will always insert the DOM element, but will display/hide it based on the condition. While ng-if will not insert the DOM element until the condition is not fulfilled.
Angular directives are used to extend HTML and DOM elements's behavior. These are the special attributes, that start with ng- prefix, instructs Angular HTML compiler ($compile) to attach a specified behavior to that DOM element.
Examples of Angular inbuilt directives include ngApp, ngInit, ngBind ,ngModel and ngClass.
The selector property instructs the Angular to display the component inside a custom tag in the index.html.
@Component({ selector: 'myApp', template: `<h1>Hi {{name}}</h1>` })
In the above example, selector tells the Angular to display component inside the custom tag 'myApp'.
<myApp>Load Component content here ...</myApp>
Angular architecture consists of 8 modules,
- Module,
- Component,
- Template,
- Metadata,
- Data binding,
- Service,
- Directive,
- and Dependency Injection.
There are 2 types, Root and feature modules. There is only one root module and many feature modules in an Angular application.
Root module is an angular module class that describes how the application is assembled and the parts fitted together. The root module is usually named as AppModule.
Every angular application has at least one module, the root module to bootstrap and launch the application. There is only one root module for an angular application.
A module groups and work as container for the different parts of application such as controllers, services, directives, pipes and so on.
npm start command usually run 2 commands parallelly. 1 command watches for typescript file changes to refresh and the other for lite-server to load the index html file on the browser and refresh as required.
Use backtick "`" instead of single quote.
RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. Angular is built on top of RXJS.
Check the variable against undefined keyword.
*ngIf= "dolRecords !== undefined"
Use logical operator such as and (&&) to evaluate multiple conditions.
Angular 2 is component based. Controllers and $scope are no longer in use and have been replaced by components and directives.
The specification for directives is considerably simplified and using @Directive annotation, a directive can be declared.
Improved dependency injection model in Angular2.
Use of TypeScript, a typed super set of JavaScript in Angular. The presence of types makes the code less prone to run-time errors.
TypeScript has generics and lambda feature.
With Angular 2 the Form Builder and Control Group are defined that makes it easy to build forms and it's validations .
ng-container is a logical container used to group nodes but is not rendered in the DOM tree as a node.
ng-container can conditionally append a group of elements, using ngif in your application, it eliminates the need to wrap them with another element.
<ng-container *ngIf="true"> <h2>Title</h2> </ng-container>
There are 3 types.
- Component,
- Attribute Directive,
- and Structural.
Directives associate behavior to elements in the DOM, consisting of Structural, Attribute and Component types.
Components are a type of directive in Angular that allows utilizing web component functionality - encapsulated, reusable elements available throughout our application.
The main difference between a component and a directive is that a component has a template, while an attribute or structural directive does not have a template.
ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.
ngAfterViewInit is also a lifecycle hook that is called after a component's view has been fully initialized.
The Constructor of the class is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better DI analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor.
ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.
A Zone is an execution context that persists across async tasks and allows the creator of the zone to observe and control execution of the code within the zone.
These execution contexts allow Angular to track the start and completion of asynchronous activities and perform tasks as required (for example, change detection).
No, Angular2 does not support more than one structural directive on the same element.
You may use the
The RouterOutlet directive tells our router where to render the content in the view.
Use brackets to pass a bindable property (a variable).
Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development process.
webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.
'ng-model' is an angular directive used for achieving two-way data binding. Any modifications to that model from the Scope/Controller will be automatically propagated to the view regardless of whether the view is asking for the updated data and any modifications to that model from the View will be immediately reflected back to the Scope/Controller.
'ng-bind' is an angular directive used for achieving one-way data binding. After the binding, any modifications to that model from the scope/controller will be automatically propagated to the view regardless of whether the view is asking for the updated data. No propagation happens for any change to the model from the view to the controller.
The forRoot is a static method and it helps to configure the modules. For example, RouterModule.forRoot.
The RouterModule also has forChild method, static method used to configure the routes of lazy-loaded modules. The forRoot and forChild are the traditional names for methods that configure services in root.
It is possible to provide the service when creating the service. When you create the service using NG CLI specify the module using (--module or -m) to provide as shown below.
ng g s KenoDataService --module=app.module
imports makes the exported declarations of other modules available in the current module.
declarations make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
providers make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as the dependency.
Angular pipes is a way to write display-value transformations that you can declare in your HTML.
A pipe takes in data as input and transforms it into the desired output. In the below example, pipe transforms a component's birthday property into a human-friendly date.
import { Component } from '@angular/core'; @Component({ selector: 'app-birthday', template: `<p>The User's birthday is {{ birthday | date }}</p>` }) export class UserBirthdayComponent { birthday = new Date(1981, 3, 15); }
The Angular Router enables navigation from one view to the other as users perform application tasks.
Angular router interpret a browser URL to navigate to a client-generated view. It also can pass parameters along to the supporting view component that help it decide dynamic content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link.
For angular 4+, use one of the below commands.
- ng version,
- ng -v.
For instance, take the structure of the Shopper Stop angular application.
e2e folder holds end to end test cases that help ensure the angular components are working correctly. This subfolder stores configuration and source files for a set of end-to-end tests that correspond to angular application.
node_modules subfolder provides/stores the npm packages required for the application.
src subfolder contains the source files related to app logic, data, and assets, along with configuration files for the initial application.
.editorconfig configuration file stores editor configuration.
.gitignore file specifies untracked files that Git should ignore.
angular.json stores CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses.
package-lock.json provides version information for all packages installed into node_modules by the npm client.
package.json configures npm package dependencies that are available to all projects in the workspace.
README.md contains introductory documentation.
tsconfig.json has default TypeScript configuration for apps in the workspace, including TypeScript and Angular template compiler options.
tslint.json stores default TSLint configuration for apps in the workspace.
Structure of src sub-folder.
app/ contains the component files in which your app logic and data are defined.
assets/ contains image files and other asset files to be copied as-is when you build your application.
environments/ contains build configuration options for particular target environments. By default, there is an unnamed standard development environment and a production ("prod") environment. You can define additional target environment configurations.
browserlist configures sharing of target browsers and Node.js versions among various front-end tools.
favicon.ico is the icon to use for this app in the bookmark bar.
index.html is the main HTML page that is served when someone visits your angular site.
main.ts is the main entry point for your app. This typescript file compiles the application with the JIT compiler and bootstraps the application's root module (AppModule) to run in the browser.
polyfills.ts provides polyfill scripts for browser support.
styles.sass lists CSS files that supply styles for a project. The extension reflects the style preprocessor you have configured for the project.
test.ts is the main entry point for your unit tests, with some Angular-specific configuration.
tsconfig.app.json inherits from the workspace-wide tsconfig.json file.
tsconfig.spec.json inherits from the workspace-wide tsconfig.json file.
tslint.json inherits from the workspace-wide tslint.json file.
Angular CLI is a command line interface to scaffold and build angular apps. It provides a scalable project structure and also handles most of the task in building the application.
Angular CLI comes with a handful of commands to set up and build your project from scratch. Below are few commands.
ng new "path_to_project"
will create a new project by installing required dependencies.
ng serve
builds your project and also it runs the project on the local server.
ng help
provides the list of ng commands for reference.
The Component decorator is an object with many properties such as,
selector specifies the tag (html identifier) used to call this component in HTML templates as any standard HTML tags.
templateUrl specifies HTML template path used to display this component. Alternatively template parameter may be used to include the HTML template inlined as a string.
styleUrls: specifies an list of URLs for CSS style-sheets for the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Shoppers-stop'; }
Services are a great way to share information among components/classes that don't know each other. Services can be injected into any component and it usually holds data/code providing data for one or more components.
To create a service using angular CLI, use the below command.
ng g service searchAPI
The above command generates 2 files, search-api.service.ts
, and search-api.service.spec.ts
, hold the code related to service and unit test specification for the service respectively.
search-api.service.ts file generated content follows:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SearchAPIService { constructor() { } }
We can create a service as singleton in Angular in 2 ways:
Declare that the service should be provided in the application root. This is done by setting
providedIn
to root on the service's @Injectable decorator as shown below. This is the preferred way to create a singleton service starting Angular 6.import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class UserService { }
- Include the service in the AppModule or in a module that is only imported by the AppModule.
Service worker is a script that runs in a web browser and manages cache of any web application. Angular applications are turned into progressive web application (PWA) after implementing service worker there by benefitted by,
- increased reliability and performance,
- eliminate additional low level coding for caching,
- optimize the end user experience on application over a slow network connection,
- minimize the risk of serving outdated content.
ngIf
directive does not show or hide an element from DOM. Instead, the ngIf directive removes or recreates a portion of the DOM tree based on the ngIf {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise, a clone of the element is reinserted into the DOM.
Angular translates the *ngIf attribute into a <ng-template>
element, wrapped around the host element. For example, consider the below code snippet.
<div *ngIf="employee" >{{employee.name}}</div>
This code will be translated as shown below by Angular.
<ng-template [ngIf]="employee"> <div>{{employee.name}}</div> </ng-template>
ng-style is used to interpolate javascript object into style attribute.
ng-style="{width: 10px}"
The above directive will be translated to style="width:10px".
ng-class directive translates your object into class attribute.
ng-class="{'highlight-class': isActive}"
The above template is translated to class="highlight-class" when isActive variable is true.
In Angular as compared to MVC, a component acts as a controller/ViewModel while template represent the "view".
Emulated view encapsulation is the default encapsulation that emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view.
Ivy is the code name for Angular's next-generation compilation and rendering pipeline. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine.
There are 3 types of directives in Angular:
Components, directives with a template.
Structural directives, changes the DOM layout by adding and removing DOM elements. Examples are NgFor and NgIf.
Attribute directives, changes the appearance or behavior of an element, component, or another directive. Examples are NgStyle and NgClass.
Structual directives are responsible for HTML Layouts, reshaping DOM structure by dynamically adding and removing/manipulating elements.
Structural directives have *(asterisk) preceding the attribute name and no square brackets nor parenthesis. This makes structural directives easy to identify.
Examples for structural directives are as follows.
- *ngIf,
- *ngFor,
- ngSwitch (*ngSwitchCase and *ngSwitchDefault).
Structural directive. | Attribute directive. |
Structural directives are responsible for HTML layout. They shape and modify the DOM's structure by adding, removing, or manipulating elements. . | Attribute directive are used as element attributes that change the appearance or behavior of an element, component, or another directive. . |
You can only apply one structural directive to a host element. | You can apply many attribute directives to one host element. |
*ngIf and *ngFor are examples. | ngStyle and ngClass are builtin attribute directives. |
The <ng-template>
is an angular element for rendering HTML. It will never get displayed directly in the view. Before rendering the view, Angular replaces the <ng-template> and its contents with a comment.
The Angular <ng-container>
is a grouping element that does NOT interfere with styles or layout because Angular doesn't put this element in the DOM.
The <ng-container> is a syntax element recognized by the Angular parser. It is not a directive, component, class, or interface. This element can replace a span tag as you may want to eliminate any styles associated with the span element, also ng-container can be used for conditional select-option list. In short, use <ng-container> as a grouping element when there is no suitable host element.
Angular comes with builtin pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.
There are 2 types of pipes: pure and impure. Pipes are pure by default. You make a pipe impure by setting its pure flag to false.
@Pipe({ name: 'exponential', pure: false })
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value such as String, Number, Boolean, Symbol or a changed object reference like Date, Array, Function or Object.
Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, even for every keystroke or mouse movement. Implement an impure pipe with great care since an expensive, long-running pipe could affect performance and user experience.
JsonPipe is an inbuilt pipe that converts a value/object into its JSON-format representation. It is usually used for debugging.
{{ value_expression | json }}
<form [formGroup] = "profileForm" > <label> First Name: <input type="text" formControlName = "firstName"></label> <label>Last Name: <input type="text" formControlName ="lastName"></label> <div formGroupName="address"> <h4>Address</h4> <label>Street: <input type="text" formControlName = "street"> </label> <label>City: <input type="text" formControlName="city"> </label> <label>State: <input type="text" formControlName="state"> </label> <label>Zip: <input type="text" formControlName="zip"> </label> </div> <button type="submit" (click)="onsubmit()" [disabled]="!profileForm.valid"> Submit</button> </form> {{profileForm.value}} {{profileForm.value | json }}
The FormBuilder service is an injectable provider that is provided with the reactive forms module.
The FormBuilder service has 3 methods: control(), group()
, and array()
. These are factory methods for generating instances in your component classes including form controls, form groups, and form arrays.
The NgForm directive powers the form element with additional features. It holds the controls you created for the elements with a ngModel
directive and name
attribute, monitors their properties and its validity.
<form #myForm="ngForm">
You must define name attribute when using [(ngModel)] in combination with a form.
AbstractControl is the base class for FormControl, FormGroup, and FormArray.
Promise. | Observable. |
A Promise handles only one event when an async operation completes or fails. | An Observable is like a Stream and accepts 0 or more (multiple) events where the callback is called for each event. |
Promise doesn't support cancelation. | Observables are cancelable. |
Promises execute immediately on creation. | Observables are declarative and computation does not start until subscription. |
Promises provide only one value. | Observables provide many values. |
Promises push errors to the child promises for error handling. | Observables subscribe() is responsible for handling errors that provides centralized and predictable error handling. |
An NgModule describes how the application components fit together. Every application has at least one Angular module, the root module that you bootstrap to launch the application. By convention, it is usually called AppModule.
The @NgModule
decorator identifies AppModule as an NgModule class. @NgModule takes a metadata object that tells Angular how to compile and launch the application.
Reference: Angular IO docs.
No. A component can be declared only in one module and that module be reused by importing it.
pleae find the game app in stackbliz.
Tree shaking is a step as part of the build process in which eliminates/drops code in your project that are not used/referenced anywhere.
A Angular components and its HTML template together defines an Angular view
Each component along with its template in Angular is represented as a view.
The embedded view is a view that is created for the view nodes specified in the ng-template. It's like a component view but it doesn't have a wrapper component element and component data like injector
createEmbeddedView is used to create a view using TemplateRef. TemplateRef is created by Angular compiler when it encounters ng-template tag in your component HTML. The view created using this method is called an embedded view.
createComponent is used to create a view using ComponentFactory. It is created by Angular compiler when you specify a component in the bootstrap property of the module so that compiler generates a factory for it. The view created using this method is called a host view.
import { Component, ViewContainerRef, ComponentFactoryResolver, NgZone, VERSION, ViewChild } from '@angular/core'; @Component({ selector: 'hello-world', template: `<h1>Hello world!</h1>`, styles: [``] }) export class HelloWorldComponent {} @Component({ selector: 'my-app', template: ` <ng-container #hw></ng-container> `, styles: [''] }) export class AppComponent { @ViewChild('hw', {read:ViewContainerRef}) vc: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) {} ngOnInit() { const factory = this.resolver.resolveComponentFactory(HelloWorldComponent); this.vc.createComponent(factory); } }
There are 4 forms.
- {{value}},
- [property]="value",
- (event)="handler",
- [(ng-model)] ="property".
Yes. ngModel modifies the behavior of an existing element by setting its display value property and responding to change events.
Service fetch data from server, also it can be used to validate user inputs.
The parent component may bind to the EventEmitter property of child that emit events and react to those events.
The child's EventEmitter property is an output property decorated with @Output()
.
CSS is the styling language that any browser understands to style webpages.
SCSS is a special type of file for SASS, a program written in Ruby that assembles CSS style sheets for a browser. SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster. SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.
The RouterOutlet is a directive from the router library used as a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet.
<router-outlet></router-outlet> <!-- Routed components displayed here -->
Guards in Angular are like components that gets executed before the route is loaded or the ones leaving the route. Guards help protect the route.
- Steep learning curve required.
- Performance may be concern in complex SPA applications.
- Limited SEO options and less accessibility for search engine crawlers.
Angular Universal also known as Angular SSR (Server side rendering) is a technology that renders Angular applications on the server.
A regular Angular application executes in the browser, rendering pages in the DOM in response to user actions. However Angular Universal executes on the server, generating static application pages that later get bootstrapped on the client.
With angular universal, the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.
Advantages of using Angular universal.
- Facilitate web crawlers through search engine optimization (SEO).
- Improve performance on mobile and low-powered devices.
- Show the first page quickly with a first-contentful paint (FCP).
Index signatures are used to define objects that is used as dictionaries.
interface KeyMap { [key: string]: number; } keyMap: KeyMap = {}; keyMap['key1'] = 4;
Yes. ngx-soap npm library we can access SOAP web services using Angular application.
ngx-soap is a simple SOAP client for Angular 6/7.
1. install ngx-soap and dependencies
npm install --save ngx-soap npm install --save buffer concat-stream core-js crypto-js events lodash sax stream uuid
2. Add NgxSoapModule to your app module.
import { NgxSoapModule } from 'ngx-soap'; ... @NgModule({ imports: [ ..., NgxSoapModule, ... ] ...
3. Inject NgxSoapService in your component/service:
... import { NgxSoapService, Client, ISoapMethodResponse } from 'ngx-soap'; ... @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { client: Client; intA = 2; intB = 3; constructor(private soap: NgxSoapService) { this.soap.createClient('assets/calculator.wsdl').subscribe(client => this.client = client); } sum() { const body = { intA: this.intA, intB: this.intB }; (<any>this.client).Add(body).subscribe((res: ISoapMethodResponse) => this.message = res.result.AddResult); } }
- IndexedDB databases store key-value pairs.
- IndexedDB is built on a transactional database model.
- The IndexedDB API is asynchronous.
- IndexedDB uses DOM events to notify you when results are available.
- IndexedDB is object-oriented.
- IndexedDB does not use Structured Query Language (SQL) and adheres to same origin policy.
Web workers allow you to run CPU-intensive computations in a background thread, freeing the main thread to update the user interface. If you find your application performs a lot of computations, such as image processing, looped mathematical calculations, using web workers can help increase your application's performance.
Use the "contextMenu" handler as shown in the below code.
<div (contextmenu)="onrightClick($event)">right click me!</div>
Use dblclick
event handler.
<a (click)="method1()" (dblclick)="method2()">
In a real-world complex application, you may want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second < router-outlet> to your app because it is in addition to the
A child route is like any other route, in that it needs both a path and a component. The one difference is that you place child routes in a children array within the parent route.
const routes: Routes = [ { path: 'first-component', component: FirstComponent, // this is the component with the <router-outlet> in the template children: [ { path: 'child-a', // child route path component: ChildAComponent, // child route component that the router renders }, { path: 'child-b', component: ChildBComponent, // another child route component that the router renders }, ], }, ];
The router supports both styles with two LocationStrategy providers.
- PathLocationStrategy, the default "HTML5 pushState" style, a LocationStrategy used to configure the Location service to represent its state in the path of the browser's URL. The RouterModule.forRoot() function sets the LocationStrategy to the PathLocationStrategy, which makes it the default strategy.
- HashLocationStrategy, the "hash URL" style, a LocationStrategy used to configure the Location service to represent its state in the hash fragment of the browser's URL.
There are two methods we can invoke using RouterModule in order to register routes: forRoot, and forChild.
The forRoot() method creates a NgModule that contains all the directives, the given routes, and the Router service itself.
The forChild() method creates a NgModule that contains all the directives and the given routes but does not include the Router service. In order to register nested routes in a lazy-loaded module, we will need to use the forChild.
APP_INITIALIZER register listeners for the Angular bootstrap process which serves as hooks during Application initialization. This way we can use such hooks to subscribe to the application bootstrap process and perform our initialization logic.
The APP_INITIALIZER is an instance of InjectionToken. It is a built-in Injection token provided by Angular.
The Angular will execute the function provided by this token when the application loads. If the function returns the promise, then the angular will wait until the promise is resolved. This will make it an ideal place to perform some initialization logic before the application is initialized.
SCSS is full of advanced features, SCSS offers variables which you can use to shorten your code. It is a great advantage over conventional CSS.
SCSS adds the feature of @import which lets you import your customized SCSS files.
Angular is a JavaScript Binding framework that binds the HTML UI and Javascript Model. This helps you to reduce your effort on writing those long lines of code for binding.
Angular helps you to build SPA by using the concept of routing. It also has lots of other features like HTTP, DI, Input(), Output() using which we don't need any other frameworks.
AngularJS | Angular | |
Versions | (1.x) | 2, 4, 5, 6,7,8, 9 and 10 |
Language | JavaScript | TypeScript |
Architecture | Controller | Component |
Mobile compliant | No | Yes |
CLI | No | Yes |
Lazy loading | No | Yes |
SEO | No | Yes |
Server side | No | Yes |
The different types of Angular directives are as follows:
- Components- directives with a template. This type of directive is the most common directive type.
- Attribute directives- directives that change the appearance or behavior of an element, component, or another directive.
- Structural directives- directives that change the DOM layout by adding and removing DOM elements.
NPM is a package manager which makes the installation of JavaScript framwork and packages easy.
"node_modules" is the folder where the packages are installed.
package.json file has all the JavaScript references needed for a project. So rather than installing one package at a time we can install all packages in one go.
Typescript is a superset of Javascript and adds types to the language. It gives a nice Object-oriented programming environment which transpiles/converts to JavaScript.It is strongly typed so we will have less type errors.
A schematic is a template-based code generator that supports complex logic. It is a set of instructions for transforming a software project by generating or modifying code. Schematics are packaged into collections and installed with npm.
Components is where you write your binding code. Module logically groups components.
Decorator defines what kind of Angular class is it. For example, if you decorate "@Component" then it says the class is an Angular component, if you specify as "@NGModule" it becomes Angular module.
This is nothing but Angular decorators such as @Component and @NgModule.
Template is an HTML view of Angular in which we can write directives. There are 2 ways of defining template, inline and separate HTML file.
There are 4 types.
- expression/Interpolation binding {{}}, for example
{{cust.customerName}} - property binding [], [(ngModel)] = "cust.customerId"
- event binding (), for example, (click) = "toggle()"
- two way binding [()] , in this case, data from controller to view is passed and on event data move from view to controller.
SPA stands for Single Page Application.
Single Page Application are applications where the main UI gets loaded once and then the needed UI is loaded on demand.
Actually, there are two ways of detecting and acting upon when an input changes in the child component in angular.
- Use the ngOnChanges() lifecycle method.
- Use input property setter.
@Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }
Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.
PWAs provide a number of advantages to users - including being installable, progressively enhanced, responsively designed, re-engageable, linkable, discoverable, network independent, and secure.
Jasmine is a JavaScript testing framework that supports a software development practice called Behaviour-Driven Development, or BDD for short. Its a specific flavour of Test-Driven Development (TDD).
Jasmine, and BDD in general, attempts to describe tests in a human-readable format so that non-technical people can understand what is being tested. However, even if you are technical reading tests in BDD format makes it a lot easier to understand whats going on.
For example, to test the below function:
function helloWorld() { return 'Hello world!'; }
describe('Hello world', () => { it('says hello', () => { expect(helloWorld()) .toEqual('Hello world!'); }); });
Sometimes in order to test a feature we need to perform some setup, perhaps it's creating some test objects. Also, we may need to perform some cleanup activities after we have finished testing, perhaps we need to delete some files from the hard drive.
These activities are called setup and teardown (for cleaning up) and Jasmine has a few functions we can use to make this easier:
beforeAll function is called once, before all the specs in a test suite (describe function) are run.
afterAll function is called once after all the specs in a test suite are finished.
beforeEach function is called before each test specification (it function) is run.
afterEach function is called after each test specification is run.
describe('Hello world', () => { let expected = ""; beforeEach(() => { expected = "Hello World"; }); afterEach(() => { expected = ""; }); it('says hello', () => { expect(helloWorld()) .toEqual(expected); }); });
Karma is a task runner for our tests. It uses a configuration file in order to set the startup file, the reporters, the testing framework, the browser among other things.
Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.
SubSink help manage multiple subscriptions. SubSink is a simple class to absorb RxJS subscriptions in an array. Call unsubscribe() to unsubscribe all of them, as you would do in your component library's unmount / onDestroy lifecycle event.
private subscriptions = new SubSink(); ngOnInit() { // Method 1 this.subscriptions.add(this.userService.getAllUsers().subscribe(data => { this.userList = data; this.userListSubject$.next(this.userList); })); // Method 2 this.subscriptions.sink = this.userService.getAllUsers().subscribe(data => { this.userList = data; this.userListSubject$.next(this.userList); }); } ngOnDestroy() { this.subscriptions.unsubscribe(); }
NgRx is a framework for building reactive applications in Angular. NgRx provides libraries for:
- Managing global and local state.
- Isolation of side effects to promote a cleaner component architecture.
- Entity collection management.
- Integration with the Angular Router.
- Developer tooling that enhances developer experience when building many different types of applications.
<input [value]="title" (input)="title=$event.target.value">
@HostListener() function decorator allows you to handle the events of the host element in the directive class.
@HostBinding() function decorator allows you to set the properties of the host element.
Permitting direct access to the DOM can make your application vulnerable to XSS attacks.
Direct access to native elements is not supported in the case of web workers.
Angular Unit Testing is used to test individual components of the applications. It is performed by using Karma and Jasmine. Jasmine is used in writing the tests and Karma is used in running those tests. We can use Async and TestBed in testing Asynchronous Code, Components, Directives and Service easier.
The CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.
To generate a coverage report run the following command in the root of your project.
ng test --code-coverage
When the tests are complete, the command creates a new /coverage folder in the project. Open the index.html file to see a report with your source code and code coverage values.
If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, angular.json:
"test": { "options": { "codeCoverage": true } }
SCAMs (single component Angular modules) are Angular modules that are scoped to a single declarable. For directives and pipes, they declare and export a single declarable.