Angular 2,4,5,6 Interview Questions - BEHIND JAVA

Angular 2,4,5,6 Interview Questions

Share This
p>Angular is one of the very fast growing technology. The early version of angular is known as Angular js (angular js 1.x versions). From the version 2.0 they completely rewrittern the language for better performance and security. Here we are mainly focusing about the interview questions which related to Angular 2.0 to Angular 6.0 versions

Why single page application?

A single-page application (SPA) is a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server. This approach avoids interruption of the user experience between successive pages, making the application behave more like a desktop application. In an SPA, either all necessary code – HTML, JavaScript, and CSS – is retrieved with a single page load, or the appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions.

What are the different component in Angular? or Explain the architecture overview of Angular?

Modules

Modules are used in Angular JS to put logical boundaries in your application. a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application.

Component

A component in Angular JS2 is the basic building block. It is visible to the end user and can be reused many times in an application.

The syntax of component looks like follows

Metadata

Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata.

  • Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator.
  • Parameters − This is set by the decorators at the constructor level.
eg: export class AppComponent {
   constructor(@Environment(‘test’ private appTitle:string) { }
}

Templates

You define a component’s view with its companion template. A template is a form of HTML that tells Angular how to render the component. A template looks like regular HTML

Data binding

Angular supports data binding, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.

Directives

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives. A directive is a class with a @Directive decorator.

What is a 'Component' in angular?

A component in Angular JS2 is the basic building block. It is visible to the end user and can be reused many times in an application.

For example, if we want to create a shopping cart application which is an online shopping cart for mobile devices in Angular JS2, the top most component would be shopping cart component which consists of child components called Welcome component, login component. Login component consists of product list component, product details component.

The syntax of component looks like follows

What is module in Angular?

Modules are used in Angular JS to put logical boundaries in your application. a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application. In Angular a module is marked with @NgModule decorator.

Here is the short example of a module

What are the different elements of @NgModule?

  • declarations - Declare views to make them privately available in this module.
  • exports - Makes the declared view public so they can be used by other modules.
  • imports - This is where you import other modules.
  • providers - Defines services that can be injected into this module’s views.
  • bootstrap - The component used to launch the app, the AppComponent by default. All apps must have at least one.

Explain how to create a simple angular application?

To get started let's create a bare-bones Angular application with a single component. To do this we need the following files:

  • app/app.component.ts - this is where we define our root component
  • app/app.module.ts - the entry Angular Module to be bootstrapped
  • index.html - this is the page the component will be rendered in
  • app/main.ts - is the glue that combines the component and page together

Types of bootstrapping angular application?

Default or Automatic Bootstrapping

It is the default way an angular application bootstraps and main.ts holds the starting point of an application.

platformBrowserDynamic().bootstrapModule(AppModule);

the platformBrowserDynamic() part creates the platform for our app module. An Angular platform is the entry point for Angular on a web page

Manual Bootstrapping

imagine a situation when the component to bootstrap the application is defined by the server during run-time. How can you bootstrap the application later when you get this information about the component ? In such situation manual bootstrapping comes in handy.

we need to specifies the component(s) in the in entryComponents so that the compiler create factories for them. Angular automatically adds all components specified in the bootstrap property to entry components that is why you usually don’t add the root component to the entryComponents.

What is the difference between "Constructor" and "ngOnInit"?

Why should `ngOnInit` be used, if we already have a `constructor`?

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses.

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component. We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice).

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

How to share data between component?

Parent to Child:

Sharing Data via Input

Child to Parent:

Sharing Data via ViewChild

Child to Parent: Sharing Data via Output() and EventEmitter

Unrelated Components:

Sharing Data with a Service

What is promises?

Promises work with asynchronous operations and they either return us a single value (i.e. the promise resolves) or an error message (i.e. the promise rejects).

In Angular a promise can be created with following syntax

search(term:string) {
  let promise = new Promise((resolve, reject) => {
    //TODO
  });
  return promise;
}

For handling http request via promise you can use the following way

 this.http.get(`https://abc.in/api/people/?search=${term}`).toPromise()
    .then((data: any) => {
      console.log(data);
    });
 

What is Observables?

An observable is essentially a stream (a stream of events, or data) and compared to a Promise, an Observable can be cancelled. It out of the box supports operators such as map() and filter().

Angular uses Rx.js Observables, and it uses out of the box when dealing with HTTP requests instead of Promises. That's why in the previous example we had to specify toPromise() to convert the Observable to a Promise

this.http.get(`https://swapi.co/api/people/?search=${searchTerm}`).subscribe((data: any) => {
          console.log(data);
        });
        
 

Here follows a complete example of observable

What are the difference between Promises and Observables? Explain the situations which we can choose each?

Promise

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.

Observable

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.

Heared about Angular CLI?

Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application.

Name some CLI commands?

  • ng new <name> - Creates a new workspace and an initial Angular app.
  • ng serve <project> [options] - Builds and serves your app, rebuilding on file changes.
  • ng add <collection> [options] - Adds support for an external library to your project.
  • ng build <project> [options] - Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.
  • ng config <jsonPath> <value> [options] - Retrieves or sets Angular configuration values.
  • ng run <target> [options] - Runs a custom target defined in your project.
  • ng test <project> [options] - Runs unit tests in a project.

How to use jquery with Angular?

  • npm install jquery — save
  • go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find the scripts: [] property, and include the path to jQuery as follows
    "scripts": [ "../node_modules/jquery/dist/jquery.min.js" ]
    
  • Now to use jQuery, all you have to do is to import it as follows in whatever component you want to use jQuery.
    import * from 'jquery';
    (or)
    declare var $: any;
    

How to detect a route change in Angular?

Solution 1:

Solution 2:

Solution 3:

List out the differences between ActivatedRoute and RouterState, with reference to Angular 2?

ActivatedRoute

Contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.

RouterState

Represents the state of the router.RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data.

RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data.

How to watch a variable in Angular?

1. You can use the ngOnChanges() lifecycle method :

2. Alternately, you can also use an input property setter as follows:

Explain about event emitters in Angular?

Use in directives and components to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.

Compare Localstorage, Cookies and session stoarge?

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.
  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie
  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted
  • The data is available only inside the window/tab in which it was set.
  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

How to do the authentication in Angular?

1. the routing authentication can be done via implementing canActivate Interface

Authentication of HTTP reuquest

Angular 2-6 Version comparison?

Angular 2.

Angular 2 comes with everything you need to build a complicated frontend web or mobile apps, form handling, data management, HTTP services, and so much more. With a rising popularity and more and more features coming to the core, the Angular team decided to rewrite the original framework, introducing Angular 2.

  • Angular 2 is based entirely on components – Angular 2 is entirely component based, so that controllers and $scope are now dead. $scope will be removed in Angular 2.0 in favor of ES6 classes
  • Support for TypeScript— you get access to all the advantages, libraries, and technologies associated with TypeScript.
  • universal server rendering –
  • Improved Data Binding –

Angular 4

After the release of Angular 2, the next big update for Angular was came i.e. Angular 4, Using angular 4 you can fully take advantage of all those features and start developing awesome applications immediately.

Angular 4 has following new features –

  • Faster and smaller – Angular 4 is now faster and smaller!
  • Animations Animations now have their own package i.e. @angular/platform-browser/animations
  • Templates – template is now ng-template. you should use the ng-template tag
  • Email Validator – In Angular 2.0, we use an email validator, using pattern option. but in Angular 4.0, there is a validator to validate an email.
  • Angular Universal: it’s possible to render Angular applications outside of the browser.

Angular 5

While the initial release is a beta build of Angular 5, the Google is clearly aiming to introduce major support for Google-driven progressive web apps with the latest development. The new version includes a build optimiser that helps to reduce the code of progressive apps designed through the framework.

The main purpose of Angular 5 is to make angular more faster. In this loading time as well as execution time has been improved.

  • Service Worker support in the CLI: Using @angular/service-worker can improve the loading performance of your applications.
  • Improved Universal & AppShell Support in the CLI: Angular CLI 1.6 comes with better support for Universal and Appshell.
  • Improved decorator error messages: The diagnostics produced by the compiler have been slightly improved, specifically when decorators contain unsupported or incorrect expressions.
  • TypeScript 2.5 support :The previous version of angular support TypeScript 2.3, Now Angular 5 officially announced that it supports TypeScript 2.5. You can upgrade TypeScript by running.
  • Support for Multiple Export Alias: In Angular 5 you can give multiple names to your components while exporting, this can help your user migrate without making changes.
  • Forms Validation in Angular 5: Angular 5 forms deal with an ability to decide when the field or form values and validity is updated.
  • Improved Animations in Angular 5

    In Angular 5, two new transition aliases are introduced:: increment and: decrement. Example:

    If you want to animate a carousel with 6 elements, with a nice animation. You declared a transition like:

    Before Angular 5

    transition(‘0 => 1, 1 => 2, 2 => 3, 3 => 4’, …)
    

    In Angular 5, you can write as –

    transition(‘:increment’)
    

Angular 6

  • TypeScript 2.7+ support: With the support for 2.7 in place, now it will be much easier to code with conditional type declarations, default declarations and strict class initialization.
  • Elements: This package is primarily designed to take an advantage of web components that are being supported by all modern browsers(Except Edge). This will allow you to create an Angular component and publish it as a Web Component
  • Stable Angular Material with CDK ( Component Development Kit): The initial version of Angular Material2 was released in March 2016 but was lacking in the number of components, stability, and compatibility with latest angular versions. Now it is more stable and compatible with Angular 6.
  • Ivy renderer: Ivy Renderer is new rendering engine which is designed to be backward compatible with existing render and focused to improve the speed of rendering and it optimizes the size of the final package.
  • Bazel Compiler: Bazel is a build system used for nearly all software built at Google. With this release, we will start having the Bazel compiler support.
  • Addition of navigationSource and restoredState to NavigationStart: Currently, in NavigationStart there is no way to know if navigation was triggered imperatively or via the location change. With navigationSource in place, the source of the navigation e.g scroll position or URL/URI change can be identified.
  • i18n: One of the major changes in Angular 6 is internationalization or i18n. In Angular 6, i18n is coming with runtime rendering so that there is no requirement to build one application per locale. The currency pipe was improved in Angular 6 in such a that it makes a lot of sense, for example, it will not round every currency value with 2 digits anymore.
  • RxJS 6.0: Angular 6 now used RxJS 6 internally. So we need to update our application accordingly. These changes provide developers an increase in performance and are easier to debug AJAX call stacks and improve modularity also, making it as backward compatible as possible
  • Tree Shaking: Angular 6 moved from modules referencing services to services referencing modules to make the Angular app smaller. Tree shaking is a build optimization step which tries to ensure any unused code does not get used in our final bundle.

What are different compilers in Angular?

Angular offers two ways to compile your application:

  • Just-in-Time (JIT), which compiles your app in the browser at runtime.
  • Ahead-of-Time (AOT), which compiles your app at build time

JIT compilation is the default when you run the ng build (build only) or ng serve (build and serve locally) CLI commands:

  • ng build
  • ng serve

For AOT compilation, include the --aot option with the ng build or ng serve command:

  • ng build --aot
  • ng serve --aot

Why compile with AOT?

Faster rendering

With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.

Fewer asynchronous requests

The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.

Smaller Angular framework download size

There's no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.

Detect template errors earlier

The AOT compiler detects and reports template binding errors during the build step before users can see them.

Better security

AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.

What is an AsyncPipe in Angular?

It’s this handy little pipe that we can use from within our templates so that we don’t have to deal with unwrapping data from Observables or Promises imperatively.

Using the subscribe() method and storing the state on the component instance, todos$.subscribe(todos => this.todos = todos)...

The | async pipe unwraps the state object directly in the component’s template,<li *ngFor=”let todo of todos$ | async”>...

What is webpack?

Webpack is a powerful module bundler. A bundle is a JavaScript file that incorporates assets that belong together and should be served to the client in a response to a single file request. A bundle can include JavaScript, CSS styles, HTML, and almost any other kind of file.

Webpack roams over your application source code, looking for import statements, building a dependency graph, and emitting one or more bundles. With plugins and rules, Webpack can preprocess and minify different non-JavaScript files such as TypeScript, SASS, and LESS files.

You determine what Webpack does and how it does it with a JavaScript configuration file, webpack.config.js.

Why using typescript in Angular?

TypeScript Has Great Tools

The biggest selling point of TypeScript is tooling. It provides advanced autocompletion, navigation, and refactoring. Having such tools is almost a requirement for large projects.

TypeScript is a Superset of JavaScript

Since TypeScript is a superset of JavaScript, you don’t need to go through a big rewrite to migrate to it. You can do it gradually, one module at a time.

TypeScript Makes Abstractions Explicit

A good design is all about well-defined interfaces. And it is much easier to express the idea of an interface in a language that supports them.

what is the use of NgZone in Angular?

NgZone is a modified api of zone.js for angular. It is used to get change detection

Explain Reactive Programming in Angular?

Reactive programming is simply to program using, and relying on, events instead of the order of lines in the code. Usually this involves more than one event, and those events happen in a sequence over time. We call this sequence of events a "stream". Think of events as anything that might happen in the future. For example, you know that Jane (a store owner) is always tweeting interesting stuff on Twitter, every time she tweets something we call that an "event". If you look at Jane's twitter feed, you have a sequence of "events" happening over time (a stream of events). Reactive programming is named so because we get to "react" to those events. For example, imagine that you're waiting for Jane to tweet a promotional code about something cool she sells in her store, and you want to "react" to that tweet, and buy the cool thing, using the promotional code. In a simplified picture, that's exactly what Reactive programming is all about.

What is Redux?

Redux is component based library which is used widely for front-end development. It is basically a tool for managing both data-state and UI-state in JavaScript applications. Redux separates the application data and business logic into its own container in order to let React manage just the view. Rather than a traditional library or a framework, it’s an application data-flow architecture. It is most compatible with Single Page Applications (SPAs) where the management of the states over time can get complex.

What are benefits of using store (ngrx) in angular 2?

Centralized, Immutable State

All relevant application state exists in one location. This makes it easier to track down problems, as a snapshot of state at the time of an error can provide important insight and make it easy to recreate issues. This also makes notoriously hard problems such as undo/redo trivial in the context of a Store application and enables powerful tooling.

Performance

Since state is centralized at the top of your application, data updates can flow down through your components relying on slices of store. Angular 2 is built to optimize on such a data-flow arrangement, and can disable change detection in cases where components rely on Observables which have not emitted new values. In an optimal store solution this will be the vast majority of your components.

Testability

All state updates are handled in reducers, which are pure functions. Pure functions are extremely simple to test, as it is simply input in, assert against output. This enables the testing of the most crucial aspects of your application without mocks, spies, or other tricks that can make testing both complex and error prone.

Heared about ngUpgrade?

NgUpgrade is a library put together by the Angular team, which we can use in our applications to mix and match AngularJS and Angular components and bridge the AngularJS and Angular dependency injection systems

Here follows some advantages of ngUpgrade

The ngUpgrade library (found in `@angular/upgrade/static`) allows AngularJS and Angular to run side-by-side while you incrementally migrate your application. ngUpgrade provides an API that lets you upgrade and downgrade your components and services, which means making them available to both frameworks.

One of the great things about AngularJS was its flexibility. You could use AngularJS inside of a .NET MVC project for data binding, or on its own to build complex SPAs, or all kinds of things in between. Unfortunately, this also means there were lots of different approaches to styling and architecting AngularJS apps. Each different application style becomes a different starting point for upgrading to Angular, and that starting point really matters in how you design your upgrade.

ngUpgrade breaks into two phases: Preparing Your Code and Migrating Your Code. Preparing your code to upgrade involves what I call the four building blocks. Migrating consists of bootstrapping both frameworks, setting up your production build to use AOT compilation, and then methodically moving pieces of your application to Angular. Once you know your app, the fundamentals of upgrading, and your desired endpoint, you’re able to customize your plan to your needs.

Getting the build setup right for your upgrade is one of the most difficult and time consuming steps of the process, but will pay off exponentially when done right. You have two choices: the Angular CLI or a custom Webpack setup. Either of these will require you to replace your script tags or task runners (like Gulp or Grunt) and move your application to ES6 modules and TypeScript. Using the CLI is ideal, but is often difficult for big AngularJS apps that are not ready to move to such an opinionated folder structure and build process. In that case, you’ll need to set up a Webpack build that can be used in both development and production.

Explain SystemJS in Angular?

When tsc compiles typescript into JavaScript, you end up with a bunch of js files on your local system. They somehow need to be loaded into a browser. Since browsers don't support native ES6 module loading yet, you have two options, either put them all into your index.html file in the correct order of dependencies, or you can use a loader to do that all for you. You specify the root for all modules, and then all files are loaded and executed by that loader in the correct order of dependencies. There are many loaders: requirejs, webpack, systemjs and others. In your particular case it's systemjs. Yes, this is a way for SystemJs to load bundles. It uses require() and exports syntax because that's the CommonJS syntax for loading bundles and you specified this type in your tsconfig.json

Webpack vs Browersify vs SystemJs for SPAs

Browserify

Browserify is perhaps the simplest bundler because it uses NodeJS require syntax to import javascript. It does not deal with any other assets other than pure javascript modules. You can also bundle your typescript/es6 app with Browserify plugins. However, you’ll definitely need to add a task manager like gulp or grunt for a production ready application as you’ll want to also hash or bundle file, add environments, regex replaces, further minification and asset management. Below is a simple Browserify gulp task that takes in a set of Browserify settings and entry point and outputs a bundle.js file.

SystemJs

Like Browserify, SystemJs uses the require syntax, but it is more compatible with other times of files. On GitHub, it calls itself the ‘universal loader’, in that it loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS. Meaning, it has a lot more built-in support for including different types of files than Webpack or Browserify. However, this comes at a cost. You have to directly tell SystemJs where to look for its dependencies

Webpack

Webpack treats everything as a module. Your css, html, javascript, fonts, images. Anything and everything can be inlined into your code if you desire. In addition to making everything a module, it also allows to you specify how you load these modules with ‘loaders’ and bundle them together into your bundle or index.html. Because webpack can bundle your entire app together , it makes tree shaking and optimising your code easy. Below, is an example from the Webpack Angular 2 starter. The Angular team has also recently switched to Webpack from SystemJs in their angular-cli

How to enable lazy loading of modules in an Angular app?

To show this relationship, let's start by defining a simple module that will act as the root module of our example application.

For now, let's focus on the root component of our application (AppComponent) where the navigation is defined.

Our navigation system has only two paths: eager and lazy. To know what those paths are loading when clicking on them we need to take a look at the routing object that we passed to the root module.

Here we can see that the default path in our application is called eager which will load EagerComponent.

Finally, our LazyComponent is very similar to EagerComponent and is just a placeholder for some text.

Explain some security practices in Angular?

PREVENTING CROSS-SITE SCRIPTING (XSS)

XSS enables attackers to inject client-side scripts into web pages viewed by other users. Such code can then, for example, steal user data or perform actions to impersonate the user. This is one of the most common attacks on the web.

HTTP-LEVEL VULNERABILITIES

Angular has built-in support to help prevent two common HTTP vulnerabilities, cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). Both of these must be mitigated primarily on the server side, but Angular provides helpers to make integration on the client side easier.

How to handle errors in Angular?

Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function.

Let’s see the code required for error handling. This code can be added on top of the chapter for CRUD operations using http.

In the product.service.ts file, enter the following code −

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.

How the angular binding works?

Basically application state change can be caused by three things

  • Events - click, submit, …
  • XHR - Fetching data from a remote server
  • Timers - setTimeout(), setInterval()

They are all asynchronous. Which brings us to the conclusion that, basically whenever some asynchronous operation has been performed, our application state might have changed. This is when someone needs to tell Angular to update the view.

Angular allows us to use native APIs directly. There are no interceptor methods we have to call so Angular gets notified to update the DOM.

Zones take care of all these things. In fact, Angular comes with its own zone called NgZone

How to create unit testcases in Angular?

Jasmine and karma are the main tools which used for unit testing

Jasmine is a javascript testing framework that supports a software development practice called Behaviour Driven Development, or BDD for short. It’s 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 what’s going on.

For example if we wanted to test this function:

function helloWorld() {
  return 'Hello world!';
}

We would write a jasmine test spec like so:

describe('Hello world', () => { 
  it('says hello', () => { 
    expect(helloWorld()) 
        .toEqual('Hello world!'); 
  });
});

Manually running Jasmine tests by refreshing a browser tab repeatedly in different browsers every-time we edit some code can become tiresome.

Karma is a tool which lets us spawn browsers and run jasmine tests inside of them all from the command line. The results of the tests are also displayed on the command line.

Karma can also watch your development files for changes and re-run the tests automatically.

Karma lets us run jasmine tests as part of a development tool chain which requires tests to be runnable and results inspectable via the command line.

How to apply animation to the angular component?

What are the types of validation in Angular?

Template-driven validation

To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.

Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors, which results in an INVALID status, or null, which results in a VALID status.

You can then inspect the control's state by exporting ngModel to a local template variable. The following example exports NgModel into a variable called name:

Reactive form validation

In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.

No comments:

Post a Comment

Pages