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




Monday, 8 June 2020

Dynamically Add And Remove Rows In Angular 7|8|9 Part-7



Dynamically Add And Remove Rows In Angular 7|8|9




In this article we will learn about how we can add or remove rows dynamically in angular. I am going to divide the problem into steps, so that you can easily understand and implement it side by side.

Below are the basic prerequisite:

1. Node js should be installed in dev system.
2. Angular CLI should be installed.
3. Any code editor ( i would prefer VS Code).

Please follow all the below steps carefully and try to implement side by side.

Step-1: Open the new Terminal window in the Visual Studio code.
Dynamically Add And Remove Row In Angular 7
Step-2: Type the below command to create the new project . 
  1. ng new dynamic-grid-example  

Step-3: Install the Bootstrap and Toastr, run the below command one after other. 
  1. npm install bootstrap  
  2.    
  3. npm install ngx-toastr --save  
Dynamically Add And Remove Row In Angular 7
Dynamically Add And Remove Row In Angular 7

Step-4: Go to the project directory by the below command: 

   cd dynamic-grid-example 




Step-5: Now create the component class. Run the below command in the terminal window.
  1. ng g c dynamic-grid

Step-6: Add the reference for bootstrap and toaster in the angular.json file.

Step-7: Type the following command to generate the model file for the class. 
  1. ng g class dynamic-grid   

Step-8Open the dynamic-grid.ts file and add the below code.



Step-9: Open the app.module.ts file present in the root folder and add the references there.
you can import ReactiveFormsModue , ToastrModule etc.

Notes: I have create dynamic-grid component inside demo module and injected demo module inside app module. So dynamic-grid component is injected inside demo module in my project, you can create dynamic-grid component inside the app module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModuleHTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModuleFormsModule } from '@angular/forms';
import { DemoModule } from './demo/demo.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
  declarations: [
    AppComponent,
    Demo2Component 
  ],

  imports: [
    BrowserModule,
    FormsModule
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot(),
    ReactiveFormsModule,
    DemoModule,
    AppRoutingModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORSuseClass: MyInterceptormulti: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step-10: Add the dynamic-grid compoment path into app routing module.



Step-11: Open the index.html file and add the reference for font-awesome. Copy the code with red background and paste into your index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Crud Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
 integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" 
crossorigin="anonymous">    
</head>    
<body>
  <app-root></app-root>
</body>
</html>


Step-12: Add the below code into dynamic-grid.component.html file.

<h1 style="color:hotpink;text-align: center;">dynamic-grid Example</h1>
<div class="container" style="margin-top: 5%">    
    <table class="table table-striped table-bordered">    
        <thead>    
            <tr>    
                <th>Action</th>    
                <th>Id </th>    
                <th>Name</th>  
                <th>Address</th>    
            </tr>    
        </thead>    
        <tbody>    
             <tr *ngFor="let dynamic of dynamicArray; let i = index;">   
              <td (click)="deleteDynamicRow(i)" style="color: red;">    
               <i class="fa fa-trash fa-2x"></i>    
              </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column1"  
class="form-control" type="text" />    
               </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column2"  
class="form-control" type="text" />    
                </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column3"  
class="form-control" type="text"/>    
                </td>            
            </tr>    
            <tr>    
              <td (click)="addDynamicRow(1)">    
               <i class="fa fa-plus fa-2x" style="color:green;"></i>    
              </td>    
            </tr>    
        </tbody>    
    </table>    
  </div>    

 Step-13: Finally, Add the below code into dynamic-grid.component.ts file.

import { ComponentOnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';  
import { DynamicGrid } from 'src/app/model/dynamic-grid';

@Component({
  selector: 'app-dynamic-grid',
  templateUrl: './dynamic-grid.component.html',
  styleUrls: ['./dynamic-grid.component.scss']
})
export class DynamicGridComponent implements OnInit {  
  constructor(private toastrToastrService) { }  
  dynamicArrayArray<DynamicGrid> = [];  
  newDynamicany = {};  
  ngOnInit(): void {   
    this.newDynamic = {column1: "1"column2: "aryan",column3:"Noida"};
      this.dynamicArray.push(this.newDynamic);  
  }  
  addDynamicRow(index) {   
    this.newDynamic = {column1: "1"column2: "aryan",column3:"Noida"}; 
      this.dynamicArray.push(this.newDynamic);  
      this.toastr.success('Dynamic row added dynamically''New dynamic row');  
      console.log(this.dynamicArray);  
      return true;  
  }  

  deleteDynamicRow(index) {  
      if(this.dynamicArray.length ==1) {  
       this.toastr.error("There is only one row , so cannot be deleted"'Warning');  
          return false;  
      } else {  
          this.dynamicArray.splice(index1);  
          this.toastr.warning('Dynamic row deleted successfully''Delete row action');  
          return true;  
      }  
  }   





You can see the final output:


In this way we learnt how to add or remove rows dynamically in angular. I hope you understood and implemented it in your project.

If you get struck any where or have confusion to understand any of the above steps, please inform me by writing you comment in the comment box, if you are satisfied then also please write some words for me. 

I will come up with some interesting topic very soon !! 


 Thank You