Skip to content

Angular

Angular

What is Routing Guard in Angular?

What is a module, and what does it contain?

What are pipes? Give me an example.

What's the difference between an Angular component and module?

What are the differences between AngularJS (angular 1.x) and Angular (Angular 2.x and beyond)?

What is a service, and when will you use it?

What is the equivalent of ngShow and ngHide in Angular?

What is the minimum definition of a component?

You have an HTML response I want to display. How do I do that?

What is a component? Why would you use it?

How can I select an element in a component template?

What is the equivalent of "ngShow" and "ngHide" in Angular?

What is the difference between *ngIf vs [hidden]?

What is the difference between "@Component" and "@Directive" in Angular?

What are some differences between Angular 2 and 4?

How would you protect a component being activated through the router?

What does this line do?

How would you run unit test?

When would you use eager module loading?

Explain the difference between Promise and Observable in Angular?

How to bundle an Angular app for production?

How to inject base href?

Can you explain the difference between Promise and Observable in Angular? In what scenario can we use each case?

What is the use of codelyzer?

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

What is difference between "declarations", "providers" and "import" in NgModule?

What is Redux and how does it relate to an Angular app?

What is AOT?

Explain the difference between "Constructor" and "ngOnInit"

How would you control size of an element on resize of the window in a component?

What is the point of calling "renderer.invokeElementMethod(rendererEl, methodName)"?

What is Reactive Programming and how to use one with Angular?

Why would you use a spy in a test?

What's new in Angular 6 and why shall we upgrade to it?

What is the difference between @Component and @Directive in Angular?

What is Protractor?

What is TestBed?

How to set headers for every request in Angular?

What does "detectChanges" do in Angular jasmine tests?

Why would you use renderer methods instead of using native element methods?

When does a lazy loaded module is loaded?

What is the need for SystemJS in Angular?

What would be a good use for NgZone service?

What is Zone in Angular?

Why would you use lazy loading modules in Angular app?

What are the lifecycle hooks for components and directives?

How would you insert an embedded view from a prepared TemplateRef?

How to detect a route change in Angular?

Name and explain some Angular Module Loading examples

What does a just-in-time (JIT) compiler do (in general)?

How do you create application to use scss? What changed for Angular 6?

When should I store the "Subscription" instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality?

What is Reactive programming and how does it relate to Angular?

Name some security best practices in Angular

Could I use jQuery with Angular?

What is ngUpgrage?

What is the default compilation for Angular 5?

Do you know how you can run angularJS and angular side by side?

What is the difference between BehaviorSubject vs Observable?

What is the Angular equivalent to an AngularJS "$watch"?

Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the difference.

How would you extract webpack config from angular cli project?

Is there no equivalent to $scope.emit() or $scope.broadcast() in Angular?

Could you provide some particular examples of using ngZone?

Name some differences between SystemJS vs WebPack?

Why angular uses url segment?

When to use query parameters versus matrix parameters?

What is Routing Guard in Angular?

Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.

Source

[↑] Back to top

What is a module, and what does it contain?

An Angular module is set of Angular basic building blocks like component, directives, services etc. An app can have more than one module.

A module can be created using @NgModule decorator.

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}
Source

[↑] Back to top

What are pipes? Give me an example.

A pipe takes in data as input and transforms it to a desired output. You can chain pipes together in potentially useful combinations. You can write your own custom pipes. Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.

Consider:

<p>The hero's birthday is {{ birthday | date }}</p>

In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

Source

[↑] Back to top

What's the difference between an Angular component and module?

Components control views (html). They also communicate with other components and services to bring functionality to your app.

Modules consist of one or more components. They do not control any html. Your modules declare which components can be used by components belonging to other modules, which classes will be injected by the dependency injector and which component gets bootstrapped. Modules allow you to manage your components to bring modularity to your app.

Source

[↑] Back to top

What are the differences between AngularJS (angular 1.x) and Angular (Angular 2.x and beyond)?

Angular and AngularJS is basically a different framework with the same name.

Angular is more ready for the current state of web standards and the future state of the web (ES6\7, immutiablity, components, shadow DOM, service workers, mobile compatibilty, modules, typescript and so on and so on... )

Angular killed many main features in AngularJS like - controllers, $scope, directives (replaced with @component annotations), the module definition, and much more, even simple things like ng-repeat has not left the same as it was.

Also:

  1. They added an angular cli.
  2. Your angular code is written in ES6 Typescript and it compiles at runtime to Javascript in the browser.
  3. You bind to your HTML similarly like how you would if in an Angular 1 directive. So variable like $scope and $rootScope have been deprecated.
Source

[↑] Back to top

What is a service, and when will you use it?

Angular services are singleton objects which get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time. The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application.

The separation of concerns is the main reason why Angular services came into existence. An Angular service is a stateless object and provides some very useful functions.

Source

[↑] Back to top

What is the equivalent of ngShow and ngHide in Angular?

Just bind to the hidden property

Source

[↑] Back to top

What is the minimum definition of a component?

The absolute minimal configuration for a @Component in Angular is a template. Both template properties are set to optional because you have to define either template or templateUrl.

When you don't define them, you will get an exception like this:

No template specified for component 'ComponentName'

A selector property is not required, as you can also use your components in a route.

Source

[↑] Back to top

You have an HTML response I want to display. How do I do that?

The correct syntax is the following:

<div [innerHTML]="theHtmlString"></div>

Working in 5.2.6

Source

[↑] Back to top

What is a component? Why would you use it?

Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule.

@Component({ selector: 'greet', template: 'Hello {{name}}!' })
class Greet {
  name: string = 'World';
}
Source

[↑] Back to top

How can I select an element in a component template?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor:

constructor(myElement: ElementRef) { ... }
Source

[↑] Back to top

What is the equivalent of "ngShow" and "ngHide" in Angular?

Just bind to the hidden property:

[hidden] = '!myVar';
Source

[↑] Back to top

What is the difference between *ngIf vs [hidden]?

*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

Source

[↑] Back to top

What is the difference between "@Component" and "@Directive" in Angular?

  • Directives add behaviour to an existing DOM element or an existing component instance.
  • A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour.

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

Source

[↑] Back to top

What are some differences between Angular 2 and 4?

Just to name a few:

  • Improvements in AOT,
  • allowing the "else" clause in ngIf,
  • support for TypeScript 2.1
  • breaking out the animations package
Source

[↑] Back to top

How would you protect a component being activated through the router?

The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more. The overall process for protecting Angular routes:

  • Create a guard service: ng g guard auth
  • Create canActivate() or canActivateChild() methods
  • Use the guard when defining routes
// import the newly created AuthGuard
const routes: Routes = [
  {
    path: 'account',
    canActivate: [AuthGuard],
  },
];

Some other available guards:

  • CanActivate: Check if a user has access
  • CanActivateChild: Check if a user has access to any of the child routes
  • CanDeactivate: Can a user leave a page? For example, they haven't finished editing a post
  • Resolve: Grab data before the route is instantiated
  • CanLoad: Check to see if we can load the routes assets
Source

[↑] Back to top

What does this line do?

@HostBinding lets you set properties on the element or component that hosts the directive.

The code applies the css class valid to whatever is using this directive conditionally based on the value of isValid.

Source

[↑] Back to top

How would you run unit test?

The Angular CLI downloads and install everything you need to test an Angular application with the Jasmine test framework.

The project you create with the CLI is immediately ready to test. Just run this one CLI command:

ng test
Source

[↑] Back to top

When would you use eager module loading?

Eager loading: To load a feature module eagerly we need to import it into application module using imports metadata of @NgModule decorator. Eager loading is useful in small size applications. In eager loading, all the feature modules will be loaded before the application starts. Hence the subsequent request to the application will be faster.

Source

[↑] Back to top

Explain the difference between Promise and Observable in Angular?

Promises:

  • return a single value
  • not cancellable
  • more readable code with try/catch and async/await

Observables:

  • work with multiple values over time
  • cancellable
  • support map, filter, reduce and similar operators
  • use Reactive Extensions (RxJS)
  • an array whose items arrive asynchronously over time
Source

[↑] Back to top

How to bundle an Angular app for production?

OneTime Setup

  • npm install -g @angular/cli
  • ng new projectFolder creates a new application

Bundling Step

  • ng build --prod (run in command line when directory is projectFolder)
  • flag prod _bundle for production

bundles are generated by default to projectFolder/dist/

Deployment

You can get a preview of your application using the ng serve --prod command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200.

For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.

Source

[↑] Back to top

How to inject base href?

When building you can modify base tag (<base href="/">) in your index.html with --base-href your-url option.

# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
Source

[↑] Back to top

Can you explain the difference between Promise and Observable in Angular? In what scenario can we use each case?

Promise

A Promise handles a single event when an async operation completes or fails. 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.

Source

[↑] Back to top

What is the use of codelyzer?

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.

Source

[↑] Back to top

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 Angular2 to indicate that Angular is done creating the component.

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". So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

Source

[↑] Back to top

What is difference between "declarations", "providers" and "import" in NgModule?

  • imports makes the exported declarations of other modules available in the current module
  • declarations are to 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 are to 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 dependency.

A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

Source

[↑] Back to top

What is Redux and how does it relate to an Angular app?

Redux is 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.

Source

[↑] Back to top

What is AOT?

The Angular Ahead-of-Time compiler pre-compiles application components and their templates during the build process. Apps compiled with AOT launch faster for several reasons.

  • Application components execute immediately, without client-side compilation.
  • Templates are embedded as code within their components so there is no client-side request for template files.
  • You don't download the Angular compiler, which is pretty big on its own.
  • The compiler discards unused Angular directives that a tree-shaking tool can then exclude.
Source

[↑] Back to top

Explain the difference between "Constructor" and "ngOnInit"

  • 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".

Source

[↑] Back to top

How would you control size of an element on resize of the window in a component?

@HostListener lets you listen for events on the host element or component.

This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.

Consider:

@HostListener('window:resize', ['$event'])
onResize(event: any) {
    this.calculateBodyHeight();
}
Source

[↑] Back to top

What is the point of calling "renderer.invokeElementMethod(rendererEl, methodName)"?

The purpose of invokeElementMethod is to invoke a method on a particular element but avoid direct DOM access (so we don’t tie our code just to the browser).

Source

[↑] Back to top

What is Reactive Programming and how to use one with Angular?

Reactive programming is programming with asynchronous data streams. An Angular application is a reactive system.

There are many ways to implement event streams or reified reactive programming. Angular embraced RxJS, and the EventEmitter class is just an implementation of RxJS/Observable.

In RxJS, you represent asynchronous data streams using observable sequences or also just called observables.

Source

[↑] Back to top

Why would you use a spy in a test?

Jasmine has a concept called spies. You can check if it was called, what parameters it had, if it returned something or even how many times it was called.

Consider:

it('can accept a post to update it', function() {
  var postToAccept = {
    title: 'Title',
    body: 'Post',
  };
  spyOn(rest, 'update').and.callThrough();
  post.accept(postToAccept);
  expect(rest.update).toHaveBeenCalledWith(postToAccept);
});
Source

[↑] Back to top

What's new in Angular 6 and why shall we upgrade to it?

  • Angular Elements - Angular Elements is a project that lets you wrap your Angular components as Web Components and embed them in a non-Angular application.
  • New Rendering Engine: Ivy - increases in speed and decreases in application size.
  • Tree-shakeable providers - a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute
  • RxJS 6 - Angular 6 now uses RxJS 6 internally, and requires you to update your application also. RxJS released a library called rxjs-compat, that allows you to bump RxJS to version 6.0 even if you, or one of the libraries you’re using, is still using one of the “old” syntaxes.
  • ElementRef<T> - in Angular 5.0 or older, is that the said ElementRef had its nativeElement property typed as any. In Angular 6.0, you can now type ElementRef more strictly.
  • Animations - The polyfill web-animations-js is not necessary anymore for animations in Angular 6.0, except if you are using the AnimationBuilder.
  • i18n - possibility to have “runtime i18n”, without having to build the application once per locale.
Source

[↑] Back to top

What is the difference between @Component and @Directive in Angular?

A @Component requires a view whereas a @Directive does not.

Directives

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

Components

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

Source

[↑] Back to top

What is Protractor?

Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor is a Node.js program built on top of WebDriverJS. Protractor runs tests against your application running in a real browser, interacting with it as a user would.

Source

[↑] Back to top

What is TestBed?

The Angular Test Bed (ATB) is a higher level Angular Only testing framework that allows us to easily test behaviours that depend on the Angular Framework.

We still write our tests in Jasmine and run using Karma but we now have a slightly easier way to create components, handle injection, test asynchronous behaviour and interact with our application.

The TestBed creates a dynamically-constructed Angular test module that emulates an Angular @NgModule.

Source

[↑] Back to top

How to set headers for every request in Angular?

You could provide a service that wraps the original Http object from Angular.

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Injectable() export class HttpClient {
    constructor(private http: Http) {}

    createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' + btoa('username:password'));
    }

    get(url) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(url, {
            headers: headers
        });
    }

    post(url, data) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
            headers: headers
        });
    }
}

And instead of injecting the Http object you could inject this one (HttpClient).

import { HttpClient } from './http-client';
Source

[↑] Back to top

What does "detectChanges" do in Angular jasmine tests?

detectChanges propagates changes to the DOM by running Angular change detection.

Source

[↑] Back to top

Why would you use renderer methods instead of using native element methods?

Angular is a platform, and the browser is just one option for where we can render our app. When we access the native element directly we are giving up on Angular’s DOM abstraction and miss out on the opportunity to be able to execute also in none-DOM environments such as:

  • native mobile,
  • native desktop,
  • web worker
  • server side rendering.

The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly. This is the recommended approach because it then makes it easier to develop apps that can be rendered in environments that don’t have DOM access, like on the server, in a web worker or on native mobile.

Source

[↑] Back to top

When does a lazy loaded module is loaded?

Lazy loading speeds up the application load time by splitting it into multiple bundles, and loading them on demand, as the user navigates throughout the app. As a result, the initial bundle is much smaller, which improves the bootstrap time.

Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have many components with complex routing.

Source

[↑] Back to top

What is the need for 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.

Source

[↑] Back to top

What would be a good use for NgZone service?

The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run.

Source

[↑] Back to top

What is Zone in Angular?

NgZone is a wrapper around Zone.js which is a library that creates a context around asynchronous functions in order to to make them trackable. Angular's change detection is heavily dependent on Zones.

Source

[↑] Back to top

Why would you use lazy loading modules in Angular app?

To load a feature module lazily we need to load it using loadChildren property in route configuration and that feature module must not be imported in application module. Lazy loading is useful when the application size is growing. In lazy loading, feature module will be loaded on demand and hence application start will be faster.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: 'app/customers/customers.module#CustomersModule',
  },
  {
    path: 'orders',
    loadChildren: 'app/orders/orders.module#OrdersModule',
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full',
  },
];
Source

[↑] Back to top

What are the lifecycle hooks for components and directives?

A component in Angular has a life-cycle, a number of different phases it goes through from birth to death. We can hook into those different phases to get some pretty fine grained control of our application.

  • constructor This is invoked when Angular creates a component or directive by calling new on the class.
  • ngOnChanges Invoked every time there is a change in one of th input properties of the component.
  • ngOnInit Invoked when given component has been initialized. This hook is only called once after the first ngOnChanges
  • ** ngDoCheck** Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.
  • ngOnDestroy This method will be invoked just before Angular destroys the component. Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.

These hooks are only called for components and not directives.

  • ngAfterContentInit Invoked after Angular performs any content projection into the components view (see the previous lecture on Content Projection for more info).
  • ngAfterContentChecked Invoked each time the content of the given component has been checked by the change detection mechanism of Angular.
  • ngAfterViewInit Invoked when the component’s view has been fully initialized.
  • ngAfterViewChecked Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.
Source

[↑] Back to top

How would you insert an embedded view from a prepared TemplateRef?

You can create an embedded view using createEmbeddedView method then attach that view to the DOM via TemplateRef:

@Component({
  selector: 'app-root',
  template: `
        <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
    `,
})
export class AppComponent implements AfterViewChecked {
  @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
  constructor() {}

  ngAfterViewChecked() {
    this.vc.createEmbeddedView(this._template, { fromContext: 'John' });
  }
}
Source

[↑] Back to top

How to detect a route change in Angular?

In Angular you can subscribe (Rx event) to a Router instance. So you can do things like:

class MyClass {
    constructor(private router: Router) {
        router.subscribe((val) => /*whatever*/ )
    }
}
Source

[↑] Back to top

Name and explain some Angular Module Loading examples

A module can be loaded eagerly, lazily and preloaded:

  • Eager loading is loading modules before application starts. Lazy loading is loading modules on demand.
  • Preloading is loading modules in background just after application starts.
  • In lazy loading and preloading, modules are loaded asynchronously.

The application module i.e. AppModule is loaded eagerly before application starts. But the feature modules can be loaded either eagerly or lazily or preloaded.

Source

[↑] Back to top

What does a just-in-time (JIT) compiler do (in general)?

A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.

This is in contrast to a traditional compiler that compiles all the code to machine language before the program is first run.

Source

[↑] Back to top

How do you create application to use scss? What changed for Angular 6?

This is how the style config in the CLI v1.x looks like in .angular-cli.json file.

"defaults": {
  "styleExt": "scss",
  "component": {}
}

But if you take a look into a config schema of angular.json file in version 6, you will no longer find this config anymore. To use SCSS, simply import you scss files (the default value is ‘src/styles.scss’) in your project level in an angular.json file like this.

{
  ...
  projects: {
    [your_project_name]: {
      ...
      architect: {
        build: {
          ...
          options: {
            styles:{
              "src/styles.scss"
            }
          }
        }
      }
    }
  }
}
Source

[↑] Back to top

When should I store the "Subscription" instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

Se should add a

private ngUnsubscribe: Subject = new Subject();

field to all components that have .subscribe() calls to Observables within their class code.

We then call

this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();

in our ngOnDestroy() methods.

Source

[↑] Back to top

Cookies and local storage serve different purposes.

  • Cookies are primarily for reading server-side,
  • Local Storage can only be read by the client-side.

So the question is, in your app, who needs this data — the client or the server? If it's your client (your JavaScript), then by all means switch to local storage. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

Source

[↑] Back to top

What is Reactive programming and how does it relate to Angular?

Reactive programming is programming with asynchronous data streams. RxJs stands for Reactive Extensions for Javascript, and it's an implementation of Observables for Javascript. 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. Angular currently uses RxJs Observables in two different ways:

  • as an internal implementation mechanism, to implement some of its core logic like EventEmitter
  • as part of its public API, namely in Forms and the HTTP module

You do not need to know Reactive Programming or RxJS in order to build even the most complex applications with Angular. It can however make some types of applications easier to architect.

Source

[↑] Back to top

Name some security best practices in Angular

  1. To systematically block XSS bugs, Angular treats all values as untrusted by default (sanitation)
  2. Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. To prevent these vulnerabilities, use the offline template compiler, also known as template injection.
  3. Avoid interacting with the DOM directly and instead use Angular templates where possible.
  4. Injecting template code into an Angular application is the same as injecting executable code into the application. So, validate all data on server-side code and escape appropriately to prevent XSS vulnerabilities on the server.
  5. Angular HttpClient provides built-in support to prevent XSRF attacks on the client side.
  6. Servers can prevent the XSSI attack by prefixing all JSON responses to make them non-executable, by convention, using the well-known string ")]}',\n". Angular’s HttpClient library recognizes this convention and automatically strips the string ")]}',\n" from all responses before further parsing.
Source

[↑] Back to top

Could I use jQuery with Angular?

First install jQuery using npm as follows

npm install jquery  save

Second 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 anywhere in your application, all you have to do is to import it as follows in app.component.ts file.

import * as $ from jquery;

Consider:

import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Look jQuery Animation working in action!';

  public ngOnInit()
  {
    $(document).ready(function(){
        $("button").click(function(){
            var div = $("div");
            div.animate({left: '100px'}, "slow");
            div.animate({fontSize: '5em'}, "slow");
        });
    });
  }
}
Source

[↑] Back to top

What is ngUpgrage?

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.

Source

[↑] Back to top

What is the default compilation for Angular 5?

  • ng serve is JiT
  • ng serve -prod is AoT
  • ng build is JiT
  • ng build -prod is AoT
Source

[↑] Back to top

Do you know how you can run angularJS and angular side by side?

In order to run both frameworks side-by-side and make components interoperable, the Angular projects comes with a module ngUpgrade. The module basically acts as an adapter facade, so we don’t really feel that there are two frameworks running side-by-side.

For this to work, four things need to interoperate:

  • Dependency Injection - Exposing Angular services into Angular 1.x components and vice-versa.
  • Component Nesting - Angular 1 directives can be used in Angular 2.x components and Angular 2.x components can used Angular 1 directives
  • Content Projection / Transclusion - Angular 1 components transclude Angular 2.x components and Angular 2.x component project Angular 1 directives
  • Change Detection - Angular 1 scope digest and change detectors in Angular >= 2.x are interleaved

Here’s what a typical upgrade process would look like:

  • Include Angular and upgrade module
  • Pick component to upgrade and change its controller and template Angular 2.x syntax (this is now an Angular 2.x component)
  • Downgrade Angular 2.x component to make it run in Angular 1.x app
  • Pick a service to upgrade, this usually requires little amount of change (especially if we’re on ES2015)
  • Repeat step 2 and 3 (and 4)
  • Replace Angular 1 bootstrap with Angular 2.x bootstrap
Source

[↑] Back to top

What is the difference between BehaviorSubject vs Observable?

BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:

  • It needs an initial value as it must always return a value on subscription even if it hasn’t received a next()
  • Upon subscription it returns the last value of the subject. A regular observable only triggers when it receives an onnext
  • at any point you can retrieve the last value of the subject in a non-observable code using the getValue() method.

Unique features of a subject compared to an observable are:

  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.

In addition you can get an observable from behavior subject using the asobservable() method on BehaviorSubject.

In Angular services, I would use BehaviorSubject for a data service as a angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component’s subscription to this data.

Source

[↑] Back to top

What is the Angular equivalent to an AngularJS "$watch"?

The solution is the set syntax from ES6. The set syntax binds an object property to a function to be called when there is an attempt to set that property.

import { Component, Input } from '@angular/core';
@Component({
  selector: 'example-component',
})
export class ExampleComponent {
  public internalVal = null;
  constructor() {}

  @Input('externalVal')
  set updateInternalVal(externalVal) {
    this.internalVal = externalVal;
  }
}
Source

[↑] Back to top

Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the difference.

JIT - Compile TypeScript just in time for executing it:

  • Compiled in the browser.
  • Each file compiled separately.
  • No need to build after changing your code and before reloading the browser page.
  • Suitable for local development.

AOT - Compile TypeScript during build phase:

  • Compiled by the machine itself, via the command line (Faster).
  • All code compiled together, inlining HTML/CSS in the scripts.
  • No need to deploy the compiler (Half of Angular size).
  • More secure, original source not disclosed.
  • Suitable for production builds.
Source

[↑] Back to top

How would you extract webpack config from angular cli project?

We usually use Angular CLI to scaffold our Angular app, but in this case, webpack file is hidden. ng eject was used if you need to do something a lot more advance or custom with webpack than what the cli provides for commands like ng build and ng serve. So it generates a webpack.config.js based on the configurations that the cli uses, so that you can then customize it further. However, that also means that you'll be able to use certain commands like ng build and ng serve.

The eject command has been temporarily disabled in Angular 6, as it is not yet compatible with the new angular.json format. The new configuration format provides further flexibility to modify the configuration of your workspace without ejecting. Ejection will be re-enabled in a future release of the CLI.

If you need to eject today, use CLI 1.7 to eject your project.

Source

[↑] Back to top

Is there no equivalent to $scope.emit() or $scope.broadcast() in Angular?

There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but it will only emit an event to the immediate parent component.

To communicate between siblings we could use:

  1. Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.
  2. Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it’s own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.
  3. Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

To communicate between a Root component and a component nested several levels deep we could use:

  1. Shared Application Model: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.
  2. Service Events: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1.
Source

[↑] Back to top

Could you provide some particular examples of using ngZone?

There would be a lot of cases when you want to use NgZone, I can name two :

  1. When you want something to run outside of Angular's change detection. Lets say we want to do some calculation when user is scrolling and don't want you to run change detection, in this case, you'd use NgZone:
constructor(private zone:NgZone){
   this.zone.runOutsideOfAngular(()=>{
      window.onscroll = ()=>{
       // do some heavy calculation :
      }
    })
  }
  1. The exact opposite of above, where you have a function that is somehow outside of Angular's zone and you want it to be inside, like when a third party library is doing some stuff for you and you want it to be bound to your Angular cycle.
this.zone.run(() => {
  $.get('someUrl').then(() => {
    this.myViewVariable = 'updated';
  });
});
Source

[↑] Back to top

Name some differences between SystemJS vs WebPack?

SystemJS:

  • SystemJS is known to be quirky with dependencies that it uses for its own polyfill
  • Importing libraries/modules from npm is not as simple as it is using WebPack
  • As you add dependencies and the code starts to grow, a fatal flaw of JSPM( systemjs) is revealed. It becomes extremely sluggish. A single refresh can take about 15-20 seconds as the browser will load 100s of different JavaScript files
  • Gulp is still required for:
  • Minification
  • Envification (envify)
  • Generating unique hashname for bundle file

WebPack:

  • Changes are now shown in milliseconds; Webpack’s dev server is designed for speed. Not only does it support incremental builds, it serves directly from memory
  • You can easily import libraries from npm (e.g. Bootstrap or Foundation) without worrying about their exact path within node_modules
  • No need of gulp. Webpack itself takes care of doing all the tasks that require Gulp in SystemJS
  • It appears that Webpack was designed from the ground-up for large applications and it shows in the development process
Source

[↑] Back to top

Why angular uses url segment?

A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix parameters associated with the segment.

Matrix parameters are tied to a path segment, while query parameters are tied to the URL. They have different semantics.

Consider:

localhost:3000/heroes;id=15;foo=foo/bar/baz
// instead of localhost:3000/heroes/bar/baz?id=15&foo=foo

The parameters are tied to heroes no to the URL. When you access the route.url, you will see this

this.route.url.subscribe((url: UrlSegment[]) => {
  let heroes = url[0];
  let heroesMatrix = heroes.parameters();
  // heroes should contain id=15, foo=foo
  let bar = url[1].path; // 15
  let baz = url[2].path; //foo
});

For matrix parameters you can also subscribe to params instead of peeling them out of url.

this.paramSubscription = this.activeRoute.params.subscribe(params => {
  const bar = params['bar'];
  const baz = params['baz'];
});

With an Angular app, the only people who really care about these parameters are us the developer. The user doesn't care. It is not a REST API where we should stick to well known semantics. For out Angular app, as long as we the developer know how to use params (whether matrix or query), it shouldn't matter which one we use.

Source

[↑] Back to top

When to use query parameters versus matrix parameters?

The differences between Matrix parameters and Query Parameters are much more than just convention.

The main differences are:

  • urls with query params won't have their response cached by intermediaries/proxies (at present)
  • matrix parameters may appear anywhere in path
  • calculating the relative uri is different
  • query params are generally abused to add new verbs instead of using existing methods on resources
  • matrix parameters are not resources, they are aspects that help reference a resource in an information space that is difficult to represent within a hierarchy
Source

[↑] Back to top