Angular Interview Questions 2

Angular Interview Questions 1

What is the Mean Stack?
Mean stack is combination four popular JavaScript-based technologies MongoDB, Express, AngularJS and Node that allows developers to develop complete web applications.

Explain Mongoose?
Mongoose is a MongoDB Object Data Modeling (ODM) library for MongoDB and NodeJS. It provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, query building, business logic hooks and more, out of the box.

How Angular is different from NodeJS.
The purpose of Angular and NodeJs is totally Different.
AngularJS is front-end framework that deals with UI and client side of an application while NodeJs is a runtime environment useful in building server-side applications.

What does a Subscribe method do in Angular 4? 
It is a method which is used with observable. Whenever the subscribe method is called, an independent execution of the observable happens.

What is an Async Pipe in Angular? 
For Observables it automatically subscribes to the observable, renders the output and then also unsubscribes when the component is destroyed so we don’t need to handle the clean up logic ourselves.
https://codecraft.tv/

What is @ViewChild in Angular? 
Essentially ViewChild and ContentChild are used for component communication in Angular.
@ViewChild() provides the instance of another component or directive in a parent component and then parent component can access the methods and properties of that component or directive.
In this way using @ViewChild() a components can communicate with a component or directive. In a parent component we can use @ViewChild() for components, directives and template reference variable with ElementRef or TemplateRef. To use @ViewChild() we need to pass child component name or directive name or template variable as an argument. simplifying viewchild, contentchild

In this example we will increase and decrease the counter using two buttons. The counter will be from a child component. Increase and decrease button will be inside parent component. We will communicate parent and child components using @ViewChild() decorator.

number.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-number',
  template: '<b>{{message}}</b>'
})
export class NumberComponent {
    message:string ='';
    count:number = 0;
    increaseByOne() {
       this.count = this.count + 1;
       this.message = "Counter: " + this.count;
    }
    decreaseByOne() {
       this.count = this.count - 1;
       this.message = "Counter: " + this.count;
    }

Now we will create the instance of NumberComponent in our parent component using @ViewChild(). 

number-parent.component.ts
import { ComponentViewChild } from '@angular/core';
import { NumberComponent } from './number.component';

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponentNumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }

Q: 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

Q: What is Webpack?

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. https://github.com/

Install with npm:
npm install --save-dev webpack

Do I need both package-lock.json and package.json?
Do you need both package-lock.json and package.json? No.
Do you need the package.json? Yes.
Can you have a project with only the package-lock.json? No.

The package.json is used for more than dependencies - like defining project properties, description, author & license information, scripts, etc. The package-lock.json is solely used to lock dependencies to a specific version number.

Q: HOW ARE JWTS USED TO AUTHENTICATE ANGULAR APPLICATIONS?
In Annular, the following Steps are used to building authentication and authorization for RESTful APIs and applications. It might help you –
  1. The users send their credentials to the server which is verified by the database credentials. If everything is verified successfully, the JWT is sent back to them.
  2. The JWT is saved in the user’s browser in local storage or in a cookie and so on.
  3. The presence of a JWT saved in the browser is used as an indicator that a user is currently logged in.
  4. The expiry time of JWT is continually checked to maintain an authenticated state in the Angular applications.
  5. The client side routes are protected and access by authenticated users only.
  6. When user sends the XHR requests for APIs, the JWT gets sent an Authorization header using your cookies or Bearer.
  7. When XHR requests coming on the server, before send back the responses it’s validated first with configured app’s secret keys. If everything is looking good then returns successfully responses other send the back to the bad request.
  8. There are several open source libraries are available for angular which are helps with JWTs and has the ability to Decode the JWT, Authorization header to XHR requests and so on.
Q: What is ng-content Directive? 
The HTML elements like p (paragraph) or h1 (heading) have some content between the tags. For example, <p>this is a paragraph</p> and <h1>this is a heading</h1>. Now, similar to this, what if we want to have some custom text or content between the angular tags like  <app-tax>some tax-related content</app-tax> This will not work the way it worked for HTML elements.  Now, in such cases, the <ng-content> tag directive is used.

Q: What does a router.navigate do?
When we want to route to a component we use router.navigate. 
Syntax: this.router.navigate([‘/component_name’]);


Q:What is Redux? 
It is a library which helps us maintain the state of the application. Redux is not required in applications that are simple with the simple data flow, it is used in Single Page Applications that have complex data flow.

Q: What is JSONP Data type?
JSONP, which stands for "JSON with Padding" (and JSON stands for JavaScript Object Notation), is a way to get data from another domain that bypasses CORS (Cross Origin Resource Sharing) rules.

Q: What is CORS?
CORS is a set of "rules," about transferring data between sites that have a different domain name from the client.

Q: 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.

Q: 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:
  1. CanActivate: Check if a user has access
  2. CanActivateChild: Check if a user has access to any of the child routes
  3. CanDeactivate: Can a user leave a page? For example, they haven't finished editing a post
  4. Resolve: Grab data before the route is instantiated
  5. CanLoad: Check to see if we can load the routes assets
Angular Route Resolver: Route resolves are nothing more than a way to pre-fetch the data a component needs before it is initialized. Usually this data comes from an API. 

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.

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

JIT - Compile TypeScript just in time for executing it:
  1. Compiled in the browser.
  2. Each file compiled separately.
  3. No need to build after changing your code and before reloading the browser page.
  4. Suitable for local development.
AOT - Compile TypeScript during build phase:
  1. Compiled by the machine itself, via the command line (Faster).
  2. All code compiled together, inlining HTML/CSS in the scripts.
  3. No need to deploy the compiler (Half of Angular size).
  4. More secure, original source not disclosed.
  5. Suitable for production builds.
Where you can deploy Node.js web application?
The easiest way to deploy your node application is to use a scalable service like Heroku, which is completely free and you only need to pay when you are using more resources.
The easiest way to deploy your Node.js web application is using Cloud server hosting like Windows, Azure, Aws, Google, Heroku etc.

Heroku is a cloud platform as a service supporting several programming languages that are used as a web application deployment model. Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
https://appdividend.com/

How to Share Data Between Angular Components?
Link 1

Why do we have to use @Injectable() in Angular Service?
@Injectable() decorator on a service is required if this service has some dependencies itself.
presence of a decorator on the class will trigger the metadata generation. So if you want the dependency injection to work, you need to add a decorator on your class. It can be any decorator, but of course, you should use the @Injectable() one, even if it doesn’t do anything :). The best practice is to add it on every service, even if it doesn’t have any dependencies on its own.
Link 1

Share data between sibling components - Angular 2+ ?
BehaviorSubject is the way, that holds some data that can be shared across any component.

//the initial value will be a string (Eric)
let currentNameSubject = new BehaviorSubject('Eric');

//To get the current value, invoke the getValue method:
currentNameSubject.getValue();
// => 'Eric'

//To change the value of an existing BehaviorSubject, call the next method with a new value:
currentNameSubject.next('Obama');

//And if we were to call getValue again:
currentNameSubject.getValue();
// => 'Obama'
Link 1 Link 2, Link 3, Link 4

How to optimize Angular app?
  1. Consider lazy loading instead of fully bundled app if the app size is more.
  2. Remove any unused 3rd party library from the application.
  3. Have all dependencies and dev-dependencies are clearly separated.
  4. Make sure the application doesn’t have un-necessary import statements.
  5. Make sure the application is bundled, uglified, and tree shaking is done.
  6. Consider AOT compilation.
How to bundle an Angular app for production
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.

What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?
There is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module."

How to use *ngIf else in Angular?
<div *ngIf = "isValid; else other_content">
content here...
</div>
<ng-template #other_content>other content here...</ng-template>

you can also use then else :
<div *ngIf="isValid;then content else other_content">here is ignored</div>
<ng-template #content>content here...</ng-template>
<ng-template #other_content>other content here...</ng-template>

What is pure function/pipe?
In JavaScript, a function is called “pure” if it has no side effect, and whose result only depends
on its input. A pure pipe is pretty much the same: the result of its transform method only depends
on arguments.
Pure pipes are the pipes which are executed only when a “PURE CHANGE” to the input value is
detected. So impure pipe executes every time irrespective of source has changed or not. which
leads to bad performance. that's why it is not recommended to use pipes for filtering data.

How change detection works Angular looks for changes to data-bound values in a change detection process that runs after every
DOM event: every keystroke, mouse move, timer tick, and server response.

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.

What is the purpose of Wildcard route? If the URL doesn't match any predefined routes then it causes the router to throw an error and crash the
app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to
match every URL. For example, you can define PageNotFoundComponent for wildcard route as below
{ path: '**', component: PageNotFoundComponent }
What's new in Angular 8?
This release is mostly about Ivy and the possibility to give it a try, but it also includes a few features and
breaking changes, namely:

  1. Differential loading - with differential loading, two bundles are created when building for production: a bundle for modern browsers that support ES2015+ and a bundle for older browsers that only support the ES5 version of JavaScript
  2. TypeScript 3.4 support
  3. Ivy - it is the new compiler/runtime of Angular. It will enable very cool features in the future, but it is currently focused on not breaking existing applications.
  4. Bazel support - it is a build tool developed and massively used by Google, as it can build pretty much  any language.
  5. Lazy-loading with import() syntax
  6. To help people migrating from AngularJS, a bunch of things have been added to the location services in Angular
  7. The service worker registration has a new option that allows to specify when the registration should take place.
  8. @angular/http has been removed from 8.0, after being replaced by @angular/common/http in 4.3 and officially deprecated in 5.0,

Explain Lazy Loading in Angular 8? 
Angular 8 comes up with support for dynamic imports in our router configuration.
This means that we use the import statement for lazy loading the module and this will be understood by
the IDEs, webpack, etc.

Angular 7:
{path: ‘user’, loadChildren:./users/user.module#UserModule’}

Angular 8:
{path: ‘user’, loadChildren: () => import(./users/user.module’).then(m => m.UserModule)};

New with Angular 8, loadChildren expects a function that uses the dynamic import syntax to import
your lazy-loaded module only when it’s needed. As you can see, the dynamic import is promise-based
and gives you access to the module, where the module’s class can be called.

What is Dependency Injection in Angular
  1. We register a service with the angular injector by using the providers property of @Component decorator or @NgModule decorator.
  2. When a component in Angular needs a service instance, it does not explicitly create it. Instead it just specifies it has a dependency on a service and needs an instance of it by including the service as a constructor parameter.
  3. When an instance of the component is created, the angular injector creates an instance of the service class and provides it to component constructor.
  4. So the component which is dependent on a service instance, receives the instance from an external source rather than creating it itself. This is called Dependency Injection. Click here

For More Questions follow another helpfull link Click here

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives