Showing posts with label angular interview questions. Show all posts
Showing posts with label angular interview questions. Show all posts

Friday, 12 June 2020

1000 Angular Facts: Angular Interview Questions with Answers Part-6


  1000 Angular Facts Q-No (71-80)






Fact:71. How to share data using @ViewChild ()  ?

Ans: Using @ViewChild () decorator we can share the data from child to parent component. 
We can inject one component into another component using decorator.

step-1 Open the parent component and import:

import { Component, ViewChild, AfterViewInit } from '@angular/core'; 
import { ChildComponent } from "../child/child.component";  

Step-2: export class ParentComponent implements AfterViewInit {  

  @ViewChild(ChildComponent) child;  
  constructor() { }  
  employeeList =[];  
  ngAfterViewInit() {  
    this.employeeList  = this.child.employeeList;  
  }  


Fact:72.  What is the significance of Route order in angular routing ?

Ans: The order of routes is important because the Router uses a first-match wins strategy when matching routes, 

> so more specific routes should be placed above less specific routes 
> List routes with a static path first, followed by an empty path route, which matches the default route. 
> The wildcard route comes in the last because it matches each and every URL and the Router selects
     it in case no other routes match first.


Fact:73. How to extract information from a route ?

Step-1 Import ActivatedRoute and ParamMap to your component

import { Router, ActivatedRoute, ParamMap } from '@angular/router';

Step-2 Inject an instance of ActivatedRoute to constructor:

constructor(
  private route: ActivatedRoute,
) {}

Step-3 write below code to the ngOnInit() method to access the ActivatedRoute and track the id parameter:

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.id = params['id'];
  });
}

Fact:74. How to display a 404 page ?

Ans: To display a 404 page,you need to set up a wildcard route with the component property set to the component
for your 404 page:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'admin', component: AdminComponent },
  { path: '**', component: SiteComponent },
  { path: '**', component: PageNotFoundComponent },  // Wildcard route for a 404 page
];

Last route with the path of ** is a wildcard route. 
The router selects this route if the requested URL doesn't match any of the paths
 earlier in the list and sends the user to the PageNotFoundComponent.


Fact:75.  Angular Universal ?

Ans: It is a tool for implementing server-side rendering of an Angular application.

# When integrating with an app, Universal generates and serves static pages on the server in response
 to requests from browsers. 
# The initial static page serves as a fast-loading placeholder while the  full application is
   being prepared for normal execution in the browser.


Fact:76. What is cross-site scripting (XSS) ?

Ans: Cross-site scripting (XSS) enables attackers to inject malicious code into the web pages. 
that can steal user data (e.g login data) or perform actions to impersonate the user. This is one of the most common attacks on the web.

# To block XSS attacks, you must prevent malicious code from entering the DOM.
if attackers can trick you into inserting a <script> tag in the DOM, they can run arbitrary code on your website. 

# The attack will not limited to <script> tags only infact many elements and properties in the DOM allow code execution, for example, <img onerror="..."> and <a href="javascript:...">

Fact:77. What is Angular’s cross-site scripting security model ?

Ans: By default Angular treats all values as untrusted to systematically block XSS bugs. 
When a value is inserted into the DOM from a template, property, attribute, style, class binding 
or interpolation, Angular sanitizes and escapes untrusted values.

Sanitization means inspection of an untrusted value and turning it into a value that's safe for the DOM.

Fact:78.  How do you perform error handling in observables?

Ans: We can handle errors by specifying an error callback on the observer instead of relying on try/catch block. 

We can define error callback as below code:

myFirstObservable.subscribe({
  next(num) { console.log('First number: ' + number)},
  error(err) { console.log('An errror occured: ' + err)}
});

Fact:79.  What is Promise ?

Ans: A promise is an API abstraction that allows us to handle asynchronous operations synchronously.

Promise Execute immediately on its creation. It Provide only one value. Uses only .then() clause.

Some Problems using Promises:

# When our application gets bigger, Promises become hard to manage. 
# A Promise is defined where data create, not where it is being used. 
# What if we want to retry a failed call?






1000 Angular Facts: Angular Interview Questions with Answers Part-8



1000 Angular Facts Q-No (81-90)




#Facts:81 How to create a Promise?

var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('I promise to return this after 1 second!');
  }, 1000);
});
promise.then(function(value) {
  console.log(value);
});

When it executes successfully, we need to call the resolve() function that
 takes the value as argument that needs to be returned, if any, or nothing. 
If anything goes wrong, you need to call the reject() method.

#Facts:82  What is RxJS? 

Ans: It is Reactive Extensions for JavaScript and it is a popular library that
is used to work with the asynchronous data streams.

RxJS helps developers to represent multiple asynchronous stream of data
and it can subscribe to the event streams by using Observer.

We can import library like this : import { interval } from 'rxjs'; 

#Facts:83 How to perform pipe chaining ?

Ans: We can chain pipes together as per our needs. 

Let's take a date pipe example which data pipe(along with parameter) and uppercase pipes as below

import { Component } from '@angular/core';
        @Component({
          selector: 'app-main',
          template: `<p>Joining date: {{  joiningData | date:'fullDate' | uppercase}} </p>` 
        })
        export class MainComponent {
          joiningData = new Date(1988, 6, 12);
        }


#Facts:84 What is Pure pipe ?

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. 
For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). 

Angular executes a pure pipe only when it detects a pure change to the input value. 

A pure change is a change to a primitive input value ( String , Number )

#Facts:85 What is Impure pipe ?

An impure pipe is called for every change detection cycle no matter whether the value or parameters changes.
i.e, we can say that an impure pipe is called on every keystroke or mouse-move.
By default every pipes in angular are pure, We can make a pipe impure by setting its pure flag to false. 

@Pipe({
  name: 'myDemoImpure',
  pure: false
})

#Facts:86 What is Reactive forms ?

“Reactive forms provide a model-driven approach for handling form inputs whose values change over time.”

>With Reactive forms we don’t have to depend on template for creating our forms.
>We use API’s provided by angular which is called the Reactive API. 
>We can use these APIs by importing a module called ReactiveModule to create the forms.

By using Reactive Forms all the declaration and structuring of the forms are to be perform in the code itself (.ts file).
Finally we can use this model in template (HTML).

#Facts:87 How to implement Reactive Forms ?

Ans: There are three steps through which we can implement Reactive Form :

1) Import Reactive forms module:

First of all, we need to import ReactiveFormsModule instead of FormsModule in our desired module class.

import { ReactiveFormsModule } from ‘@angular/forms’;

2)In component class define the form(i.e formGroup).

3)Link this form class to your HTML form.

#Facts:88 How to define the form (formGroup) in a component class ?

Ans: FormGroup: A FormGroup aggregates the values of each child FormControl into one object with each control name as the key.

FormControl: input fields in our form will be mapped with the formControl. 
The formControl is like input box,dropdown-list, radio buttons,  select box etc. 
This form control will contain the value and validations of form field.

We will create formGroup and then inside this formGroup we will create different formControl’s 
objects as per our need.In this way our formGroup will contain a group (collection) of form controls. 
And in this way our form is ready to be use in our template.

ngOnInit() {
    this.loginForm = new FormGroup({
      email: new FormControl(null),
      password: new FormGroup({
            user_password: new FormControl(null),
            user_confirmPassword: new FormControl(null),
        }),
    });
  }


#Facts:89 How to Connect this form to your template ?

Now, our Form is ready to be bind with our template like below:

<form [formGroup]=”loginForm” (ngSubmit)=”onSubmit()”></form>

formGroup: Binds the Form to the FormGroup we created in component i.e. loginForm.
ngSubmit: It will triggered when we submit the form.
formControlName: all the form fields must have formControlName, and it should be exactly the same as given in .ts file.

<input type=”text” placeholder=”Name” formControlName=”user_name”>

Example:

  <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

        <div class="form-group">
              <!-- Username -->
              <label for="username">UserName: <span class="lblError">*</span></label>
              <div class="controls">
                <input type="text" id="username" placeholder="Name" 
                 class="form-control" formControlName="user_name">
              </div>
        </div>

  </form>

Finally onSubmit() method in our component class will submit the form.

onSubmit() {
console.log(this.loginForm);
console.log(this.loginForm.get(‘user_name’).value);
}

#Facts:90 What is zone in angular?

A Zone is an execution context that persists across async tasks. 

Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events.

We can think of it as thread-local storage for JavaScript VMs. 

Know more about Zone here - https://angular.io/guide/zone


Some Useful Resources : 




Thank You




Friday, 5 June 2020

1000 Angular Facts | Q(52-54) Check Box Control | Part-4



1000 Angular Facts | Check Box Control | Part-4










1000 Angular Facts | Password and Confirm Password Validation | Part-3


Password & Confirm Password- Part-3







1000 Angular Facts Q-NO (56-70) Part-5

           
1000 Angular Facts Part-5




56.Change Detection in Angular detects any changes and based on the changes it will update the HTML DOM.

In change detection Angular runs over the bindings, evaluates expressions and compares them to the previous values and updates the DOM when required.

By default the change detection goes through every node of the tree to see if it changed, and it does it on every browser event

57. There are two different Change Detection strategies are supported.

  •     ChangeDetectionStrategy.Default.
  •     ChangeDetectionStrategy.OnPush.

58. Every Angular application must have one parent module which is called app module and it contains the list of different items which are listed below.
• Components
• Service providers
• Custom modules
• Routing modules
• Pipes

59. PrimeNg is a collection of reach UI components for Angular.

https://www.primefaces.org/primeng/

PrimeNG is available at npm, if you have an existing application run the following command to download it to your project.
npm install primeng --save
npm install primeicons --save

60. To Add ngx-bootstrap and Bootstrap :

step-1:
install ngx-bootstrap and Bootstrap
npm install ngx-bootstrap bootstrap --save

step-2: 
add styles to angular.json:

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

61. An impure pipe is called for every change detection cycle no matter whether the value or parameters changes.

 i.e, An impure pipe is calls on every keystroke or mouse-move.

62. Class decorator: A decorator that appears immediately before a class definition, which declares the class to be of the given type and provides metadata suitable to the type.

The following decorators can declare Angular class types:
@Component()
@Directive()
@Pipe()
@Injectable()
@NgModule()


63. Differential loading: is build technique that creates two bundles for an application. Smaller bundle is for modern browsers and larger bundle allows the application to run correctly in older browsers (i.e IE11) that do not support all modern browser APIs.

64. Dynamic component loading: A technique for adding a component to the DOM at run time. Requires that you exclude the component from compilation and then connect it to Angular's change-detection and event-handling framework when you add it to the DOM.

65. @NgModule: metadata is used to tell the Angular compiler what components to be compiled for this module and how to link this module with other modules.

@NgModule({
  declarations: [
    AppComponent,
    Demo2Component 
  ],
  imports: [
    BrowserModule,
    FormsModule,   
    AppRoutingModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

66. What are the types of feature modules?

Below are the five categories of feature modules:

Domain: Deliver a user experience dedicated to a particular application domain(For example, place an order, registration etc)
Routed: Domain feature modules whose top components are the targets of router navigation routes.
Routing: Provides routing configuration for another module.
Service: Provides utility services such as data access and messaging(For example, HttpClientModule)
Widget: It makes components, directives, and pipes available to external modules'

67.How to change default port number other than 4200?

Ans. If you have created new Angular app and server the app using ng serve, then our app will be executed
on URL localhost:4200, but we can change it using additional flag along with ng serve which is –port.
ng serve --port 4300

68.How to change the default protocol other than HTTP?

Ans. By default, the Angular application works on HTTP protocol which is not secure to use, so angular provide provision to change it to HTTPS which is an encrypted connection between client and server.

We can use additional flag along with command ng serve which is –ssl and we can enable it using Boolean value
true/false.
ng serve --ssl=true
Now we will be able to run our Angular app using HTTPS securely, by default –ssl value is false.

69.DatePipe: Formats a date value according to locale rules.

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}
{{ dateObject | date }}               // output is 'Jun 15, 2015'
{{ dateObject | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObject | date:'shortTime' }}   // output is '9:43 PM'


70.These are the various NgModule metadata properties:
• Declaration
• Imports
• Exports
• Providers
• Bootstrap
• entryComponent
• Id
• Jit
• Schemas


Thank You