Angular

Angular 11 How to convert HTML to image?

Angular 11 How to convert HTML to image

Angular 11 How to convert HTML to image, This article will tell the developer how to change over HTML into an image utilizing the html-to-image NPM bundle. developer can change over any Dom components into a image, Dom components like div, length, table, and so forth

By utilizing html-to-image bundle client can change HTML over to an image, a developer can change HTML over to JPEG, PNG, SVG, BLOB(Binary Large Object), This model gives you a straightforward and simple approach to change Angular 11 HTML over to Image.

Angular 11 How to convert HTML to Image Example

  • Step 1 – Create a new Angular 11 app
  • Step 2 – Install html-to-image Package
  • Step 3 – Add HTML into a view file
  • Step 4 – Add code in Component .ts file
  • Step 5 – Run Angular app

Step 1 – Create a new Angular 11 app

First of all, open your command prompt and execute the following command to create a new Angular 11 app.

ng new htmltoImage

Step 2 – Install html-to-image Package

In this step, We will install html-to-image using node package module, open the terminal and execute the following command in the terminal.

npm install --save html-to-image

Step 3 – Add HTML into a view file

In this step, We will add HTML code in a view file so visit the src/app/app.component.html file and add your HTML code

 

<div id="image-section">
  <h1>Hello world!</h1>
</div>
 
<button type="button" (click)="generateImg()">GenerateImage</button>

In the above code, I have added the id attribute because this package will access the DOM Elements and generate an image.

Step 4 – Add code in Component .ts file

import { Component } from '@angular/core';
import * as htmlToImage from 'html-to-image';
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'htmltoImage';
 
  generateImg(){
    var node:any = document.getElementById('image-section');
    htmlToImage.toPng(node)
      .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
      })
      .catch(function (error) {
        console.error('Error, something is missing!', error);
      });
  }
}
Step 5 –

Step 5 – Run Angular app

ng serve

How to create new components in Angular using the CLI

How to create new components in Angular using the CLI

How to create new components in Angular using the CLI : It just so happens, when creating your own new components in Angular, you can finish the cycle totally by hand. That was useful for learning the subtleties of what goes in to an Angular Component. Well we as a whole like automation, and you can really build another Angular command automatically using the Angular CLI, That sounds magnificent as less composing code is a reward in my book. How about we take a stab at building another Angular Component yet this time, we’ll utilize that extremely helpful Angular command line interface.

So before you start generating component using the CLI, please setup Angular app locally on your system. if you already setup angular app skip this step and move to Step 2 : CLI Component Generation

Step 1: Angular App Installation :

See how to install Angular 
after installation move to Step 2 below.

Step  2 : CLI Component Generation

You’ll want to have the ng serve process already running in a command line window for your application. Then, you can open another instance of the command line and type ng generate component edit-new-corporate to create a new edit-new-corporate component.

PS D:\corporateApp> ng g c components/edit-new-corporate
or 
PS D:\corporateApp> ng genarte component components/edit-new-corporate

> corporateApp@0.0.0 ng D:\corporateApp
> ng "g" "c" "components/edit-new-corporate"

CREATE src/app/components/edit-new-corporate/edit-new-corporate.component.html (33 bytes)
CREATE src/app/components/edit-new-corporate/edit-new-corporate.component.spec.ts (700 bytes)
CREATE src/app/components/edit-new-corporate/edit-new-corporate.component.ts (322 bytes)
CREATE src/app/components/edit-new-corporate/edit-new-corporate.component.scss (0 bytes)

Alright exceptionally interesting! It seems as though the CLI naturally made the new folder to hold our new component in src/components/edit-corporate. Likewise we see four new files related with the naturally created component.

edit-new-corporate.component.html

<p>
  edit-new-corporate works!
</p>

edit-new-corporate.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { EditNewCorporateComponent } from './edit-new-corporate.component';

describe('EditNewCorporateComponent', () => {
  let component: EditNewCorporateComponent;
  let fixture: ComponentFixture<EditNewCorporateComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ EditNewCorporateComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EditNewCorporateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

edit-new-corporate.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-edit-new-corporate',
  templateUrl: './edit-new-corporate.component.html',
  styleUrls: ['./edit-new-corporate.component.scss']
})
export class EditNewCorporateComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

edit-new-corporate.component.css

/* todo: add your styles here */

How to Add Bootstrap to Angular

How to Add Bootstrap to Angular

How to Add Bootstrap to Angular : In this article , we will tell you the best way to add Bootstrap to the Angular application. This instructional exercise utilizes Bootstrap 4 and Angular 9. We will tell you the best way to introduce the bootstrap CSS.

What is Bootstrap:

The bootstrap is a responsive mobile-first CSS framework for building Web Applications. It is open source and has all the features like Sass variables, mixings, responsive grid system, prebuilt components, and powerful JavaScript plugins.

Bootstrap consists of few CSS files & JS files.

The CSS files contains all the styles definitions.

Many of bootstrap components require the use of JavaScript to function. For Example, carousels, drop-down menus, auto-suggest, etc require bootstraps.js file. It also has dependency on jQueryPopper.js.

Step 1 : Create a new Angular Application

ng new Bootstrap-example

Step 2 : Adding Bootstrap CSS File –

Assuming you are not utilizing any of the components that utilization JavaScript, you don’t have to introduce JS documents. There are a couple of manners by which you can add the CSS Files.

We can introduce the Bootstrap CSS document in one of the accompanying ways

  • You can use the CSS file from a CDN
  • Also, copy the bootstrap.min.css file to a local folder
  • Install the bootstrap npm package

Once introduced, you can remember it for the application by utilizing the one of the techniques

  • You can add it in index.html using the link tag
  • Alos, include it in angular.json
  • Import it in styles.css

Add Bootstrap using the CDN –

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
 
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bootstrap CSS 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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"  crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Alternatively, you can use the @import directive in the styles.css file

@import "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"

Install the bootstrap package :

This way is recommended to everyone to add Bootstrap to Angular :

Run the following command to install the latest version of Bootstrap to your Application.

npm install --save bootstrap

This will add the bootstrap files to the node_modules/bootstrap directory.

Open the angular.json file and locate the projects -> Bootstrap-example (your project name) -> architect -> build -> styles node.

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

Also, you can just add the @import directive to import it in the styles.css

@import "~../node_modules/bootstrap/dist/css/bootstrap.min.css";

Step 3: Run your app using the following command

ng serve

 

Angular Google Bar Chart Example

Angular Google Bar Chart

Angular Google Bar Chart :

Google chart tools are powerful, simple to use, and free. Try out our rich gallery of interactive charts and data tools. Get started Chart Gallery. insert_chart Rich Gallery Choose from a variety of charts. From simple scatter plots to hierarchical treemaps, find the best fit for your data.

This instructional exercise shows you Angular google bar graph model. it’s straightforward illustration of Angular google bar graph npm. This post will give you straightforward illustration of Angular precise google-graphs google bar diagram . Here you will figure out how to add google bar graph in Angular .

you can without much of a stretch add google programming interface bar graph in Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 and Angular 12 form application.

In this model we will utilize Angular google-graphs npm bundle to make google programming interface bar outline model in Angular 11 application. we will essentially introduce that Angular google-graphs npm bundle and use GoogleChartsModule module to make code.

Along these lines, we should see cry step and get qr code as like roar screen capture:

Step 1: Create New App

ng new myNewApp

Step 2: Install angular-google-charts npm Package

Add angular-google-charts in our angular application by using following command.

npm install angular-google-charts

Step 3: Import GoogleChartsModule

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { GoogleChartsModule } from 'angular-google-charts';
   
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    GoogleChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Update Ts File

src/app/app.component.ts

import { Component } from '@angular/core';
   
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    
  chartData = {
      type: 'BarChart',
      data: [
      ["Pendrive",  500],
      ["Hard Disk",  800],
      ["Charger",  400],
   ],
   chartColumns: ['Sweets', 'Sell'],
   width: 1000,
   height: 400
  };
     
}

Step 5: Update HTML File

<google-chart 
    [type]="chartData.type" 
    [data]="chartData.data" 
    [columns]="chartData.chartColumns" 
    [width]="chartData.width"
    [height]="chartData.height">     
</google-chart>

Now run your application using the following command

ng serve

 

Solved – can’t bind to ‘formgroup’ since it isn’t a known property of ‘form’

can’t bind to ‘formgroup’ since it isn’t a known property of ‘form’

Can’t bind to ‘formgroup’ since it isn’t a known property of ‘form’ :  Whenever start with Angular App, everyone needs to start with form kind of information, So In most of the cases we start collect user information using form in Angular. Creating form and giving it name is the process of Angular, We declare the form name and use it in the HTML form. While executing the application It start throwing an error.  Let’s checkout this with code example.

app.component.html

<form [formGroup]="myForm">
  Naam: <input type="text" formControlName="name"><br>
  Age: <input type="number" formControlName="age">

  <button>Submit</button>
</form>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
    myForm: FormGroup;

    constructor(private fb: FormBuilder) { }

    ngOnInit() {
        this.myForm = this.fb.group({
            name: ['', Validators.required],
            age: ['', Validators.required]
        });
    }
}

Error after running app

Can't bind to 'formgroup' since it isn't a known property of 'form'

In order to solve can’t bind to ‘formgroup’ since it isn’t a known property of ‘form’ error you need to import ReactiveFormsModule in each submodule file.

app.module.ts

 import { FormsModule, ReactiveFormsModule } from '@angular/forms';`

@NgModule({
  declarations: [
    AppComponent,
  ]
  imports: [
    FormsModule,
    ReactiveFormsModule,
    yourModule,
],
...

You will have to import ReactiveFormsModule in your yourModule like this:

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

...

@NgModule({
  imports: [
    ...,
    FormsModule,    //import here
    ReactiveFormsModule //import here
  ],
  declarations: [...],
  providers: [...]
})

export class yourModule {}

 

Like us on facebook

Angular Crop Image Before Upload with Preview

Angular Crop Image Before Upload with Preview

Angular Crop Image Before Upload with Preview : In this article, we will talk about Angular crop picture before upload to the application . This post will give you straightforward illustration of Angular cropper model. you’ll learn picture upload with crop in Angular. This article goes in nitty gritty on Angular  picture upload with crop utilizing cropper.

In the event that you need to utilize picture transfer with crop, you can undoubtedly utilize ngx-image-cropper npm package. it will give you Cropping, Zooming, Scaling, and Preview usefulness while uploading time. it’s effectively use with your Angular.

In this model, I will give you bit by bit clarification how you can upload transfer in crop in Angular application.

Step 1: Create New App

Create Angular app using the following command :

ng new ngPicCrop

Step 2: Install Npm Packages : 

In this progression, we will introduce ngx-image-cropper npm package for upload picture crop work in precise.

npm install ngx-image-cropper --save

Step 3: Import ImageCropperModule

Now, here we will import ImageCropperModule from ngx-image-cropper and then we add on declarations part. so let’s update app.module.ts file as like bellow:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
  
import { ImageCropperModule } from 'ngx-image-cropper';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ImageCropperModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Step 4: Update Component ts File : 

Here, we will refresh app.component.ts document here, in this record we will compose fileChangeEvent(), imageCropped(), imageLoaded(), cropperReady() and loadImageFailed() that gave by ngx-image-cropper.

You can refresh as howl app.component.ts document.

src/app/app.component.ts

import { Component } from '@angular/core';
import { ImageCroppedEvent } from 'ngx-image-cropper';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngImageCrop';
  
  imageChangedEvent: any = '';
    croppedImage: any = '';
  
    fileChangeEvent(event: any): void {
        this.imageChangedEvent = event;
    }
    imageCropped(event: ImageCroppedEvent) {
        this.croppedImage = event.base64;
    }
    imageLoaded() {
        /* show cropper */
    }
    cropperReady() {
        /* cropper ready */
    }
    loadImageFailed() {
        /* show message */
    }

Step 5: Update HTML File : 

<div class="container">
    <div class="card">
      <div class="card-header">
          Angular Crop Image Tutorial Example - ItSolutionStuff.com
      </div>
      <div class="card-body">
        <input type="file" (change)="fileChangeEvent($event)" />
        <div class="row" style="margin-top: 15px;">
            <div class="text-center col-md-8">
                <h5>Crop Image</h5>
                <image-cropper 
                [imageChangedEvent]="imageChangedEvent" 
                [maintainAspectRatio]="true" 
                [aspectRatio]="4 / 4"
                [resizeToWidth]="256" 
                format="png" 
                (imageCropped)="imageCropped($event)" 
                (imageLoaded)="imageLoaded()"
                (cropperReady)="cropperReady()" 
                (loadImageFailed)="loadImageFailed()"></image-cropper>
            </div>
            <div class="text-center col-md-4">
                <h5>Preview</h5>
                <img [src]="croppedImage" />
            </div>
        </div>
      </div>
    </div>
</div>

Now you run your Angular app by following command :

ng serve

 

Output :

Angular Crop Image Before Upload with Preview

Angular Crop Image Before Upload with Preview

Angular Display JSON Data in Table Example

Angular Display JSON Data in Table Example

Angular Display JSON Data in Table : This instructional exercise will give you illustration of Angular showcase json data in table. you can comprehend an idea of how to show information in Angular . this model will help you Angular show information in table. I disclosed just about how to show information in Angular. Okay, how about we plunge into the means.

At some point we need to show our information in table arrangement for front end. we will utilize *ngfor mandate for show information in table. we will likewise utilize bootstrap for showing information in Angular application.

JSON is an abbreviation for JavaScript Object Notation, is an open standard organization, which is lightweight and text-based, planned expressly for intelligible information exchange. It is a language-free information design. It upholds pretty much every sort of language, structure, and library.

How about we see straightforward after advance to done basic model that will help you to showing information in Angular application.

 

Create New App

Assuming you are doing model without any preparation, You can undoubtedly make your Angular application utilizing cry order:

ng new my-app

In this record we will make understudies object cluster utilizing Student interface. so how about we see howl record code.

src/app/app.component.ts

import { Component } from '@angular/core';
  
interface Employee{
    id: Number;
    name: String;
    email: String;
    gender: String;
}
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
    
  students: Employee[] = [
    {
      id: 1,
      emp_code : "3505",
      name: "Rohit",
      email: "rohit@gmail.com",
      gender: "male"
      
    },
    {
      id: 2,
      emp_code : "3506",
      name: "Amit",
      email: "amit@gmail.com",
      gender: "male"
    },
    {
      id: 3,
      emp_code : "3507",
      name: "Kumkum",
      email: "kumkum@gmail.com",
      gender: "female"
    },
    {
      id: 4,
      emp_code : "3508",
      name: "Ajit",
      email: "ajit@gmail.com",
      gender: "male"
    },
    {
      id: 5,
      emp_code : "3509",
      name: "Mohit",
      email: "mohit@gmail.com",
      gender: "male"
    },
  ]
}

In this step, we will write code for display data of employee object array variable using ngfor directive.

I have used bootstrap class.

src/app/app.component.html

<div class="container"> 
  <table class="table table-striped">
    <thead>
        <tr>
          <th>S.no</th>
          <th>Name</th>
          <th>Employee Code</th>
          <th>Email</th>
          <th>Gender</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let emp of employee">
        <td>{{ emp.id }}</td>       
        <td>{{ emp.name }}</td>
        <td>{{ emp.emp_code}}</td>       
        <td>{{ emp.email }}</td>  
        <td>{{ emp.gender }}</td>     
      </tr>
    </tbody>
  </table>
</div>

Presently you can run your application using following command.

ng serve

 

Output :

Angular Display JSON Data in Table Example

Top Angular Interview Questions and Answers

Top Angular Interview Questions and Answers

Top Angular Interview Questions and Answers : Expecting taking care of your shocking circumstance of an Angular Developer? On the other hand, essentially proposing to change to being an Angular subject matter expert? In this article, we will take a gander at a touch of the habitually introduced smart demands that you can need to be coming your bearing during an Angular get-together for crafted by an Angular planner.

In spite of these idea based solicitations, there will be a requirement for a (or possibly different) coding test(s). Tolerating you need to change immense Angular contemplations before the get-together, The Complete Angular Course: Beginner to Advanced course from Udemy will end up being of staggering assistance. Nearby Angular solicitations, you’ll in like way be asked standard social affair demands. Here is a rule 189 Programming Questions and Solutions that will invigorate you exceptionally fast.

Top Angular Interview Questions and Answers

In any case, ready to see how well your plan is going? Moving along, here we present you for certain critical Angular requests questions and answers that you might expect in your gathering. These requests are similarly genuine for your Angular 6 requests questions and Angular 7 Interview Questions.

Question: What is Angular?

Answer: Angular is a TypeScript-based open-source web application system, created and kept up with by Google. It offers a simple and incredible method of building front end online applications.

Question: Why was Angular presented as a client side structure?

Answer: Traditionally, VanillaJS and jQuery were utilized by designers to develop unique sites. As the sites turned out to be more complex with added features and functionality , it was difficult for the designers to keep up with the code. Also, there was no arrangement of information dealing with offices across the perspectives by jQuery. In this way, Angular was worked to resolve these issues, subsequently, making it simpler for the engineers by partitioning code into more modest pieces of data that are known as Components in Angular.

Customer side structures grant the improvement of cutting edge web applications like SPAs which, whenever created by VanillaJS, is a more slow interaction.

 

Question: Define the ng-content Directive?

Answer: Conventional HTML components have some substance between the labels. For example:

<p>Put your section here</p>

Presently think about the accompanying instance of having custom content between Angular labels:

<app-work>This will not work like HTML until you use ng-content Directive</application work>

In any case, accomplishing so will not work the manner in which it worked for HTML components. To make it work very much like the HTML model referenced above, we need to utilize the ng-content Directive. Also, it is useful in building reusable components.

Find out about the ng-content mandate.

Question: Please clarify the different highlights of Angular.

Answer: There are a few highlights of Angular that make it an optimal front end JavaScript structure. Generally significant of them are portrayed as follows:

Availability Applications

Precise permits making open applications utilizing ARIA-empowered parts, inherent a11y test foundation, and designer guides.

Angular CLI

Angular offers help for command line interface devices. These apparatuses can be utilized for adding components, testing, moment sending, and so forth

Activity Support

Precise’s instinctive API permits the making of elite, complex movement courses of events with very little code.

Cross-Platform App Development

Angular can be utilized for building a proficient and amazing work area, local, and reformist web applications. Angular offers help for building local portable applications utilizing Cordova, Ionic, or NativeScript.

Precise permits making elite, disconnected, and zero-venture establishment reformist web applications utilizing current web stage abilities. The famous JS structure can likewise be utilized for building work area applications for Linux, macOS, and Windows.

Code Generation

Angular can change over formats into profoundly streamlined code for present day JavaScript virtual machines.

Code Splitting

With the new Component Router, Angular applications load rapidly. The Component Router offers programmed code-parting so just the code needed to deliver the view that is mentioned by a client is stacked.

Cooperative energy with Popular Code Editors and IDEs

Angular offers code fulfillment, moment blunders, and so forth with mainstream source code editors and IDEs.

Layouts

Permits making UI sees with a straightforward and incredible layout grammar.

Testing

Angular allows you to complete regular unit tests utilizing Karma. The Protractor permits running quicker situation tests in a steady manner.

Question: What are Lifecycle hooks in Angular? Clarify some life cycles hooks

Answer: Angular parts enter its lifecycle from the time it is made to the time it is obliterated. Angular hooks give approaches to take advantage of these stages and trigger changes at explicit stages in a lifecycle.

ngOnChanges( ): This technique is called at whatever point at least one info properties of the component changes. The hooks  gets a SimpleChanges object containing the past and current values of the property.

ngOnInit( ): This hooks gets called once, after the ngOnChanges hook.

It introduces the component and sets the information properties of the part.

ngDoCheck( ): It gets called after ngOnChanges and ngOnInit and is utilized to distinguish and follow up on changes that can’t be identified by Angular.

We can carry out our change recognition calculation in this hooks .

ngAfterContentInit( ): It gets called after the main ngDoCheck hooks . This hooks reacts after the substance gets projected inside the part.

ngAfterContentChecked( ): It gets called after ngAfterContentInit and each ensuing ngDoCheck. It reacts after the projected substance is checked.

ngAfterViewInit( ): It reacts after a component ‘s view, or a youngster component ‘s view is introduced.

ngAfterViewChecked( ): It gets called after ngAfterViewInit, and it reacts after the part’s view, or the kid component ‘s view is checked.

ngOnDestroy( ): It gets called not long before Angular obliterates the part. This hooks can be utilized to tidy up the code and disconnect occasion controllers.

Question: Could we make a precise application to deliver on the worker side?

Answer: Yes, we can, with Angular Universal, an innovation given by Angular fit for delivering applications on the worker side.

The advantages of utilizing Angular Universal are:

Better User Experience: Allows clients to see the perspective on the application quickly.

Better SEO: Universal guarantees that the substance is accessible on each web index prompting better SEO.

Loads Faster: Render pages are accessible to the programs sooner, so the worker side application stacks quicker.

Question: Explain Dependency Injection?

Answer: Dependency infusion is an application configuration design that is executed by Angular and structures the center ideas of Angular.

Allow us to comprehend in a nitty gritty way. Conditions in Angular are administrations which have a usefulness. Different components and orders in an application can require these functionalities of the help. Precise gives a smooth system by which these conditions are infused into components and mandates.

Question: What is string interpolation in Angular?
Answer: Also referred to as moustache syntax, string interpolation in Angular refers to a special type of syntax that makes use of template expressions in order to display the component data. These template expressions are enclosed within double curly braces i.e. .

The JavaScript expressions that are to be executed by Angular are added within the curly braces and the corresponding output is embedded into the HTML code. Typically, these expressions are updated and registered like watches as a part of the digest cycle.

Question: What is Angular Material?

Answer: It is a UI part library. Rakish Material aides in making alluring, predictable, and completely utilitarian pages just as web applications. It does as such while following current website composition standards, including program transportability and smooth debasement.

Question: What is AOT (Ahead-Of-Time) Compilation?

Answer: Each Angular application gets gathered inside. The Angular compiler takes in the JS code, gathers it and afterward delivers some JS code. This happens just once per event per client. It is known as AOT (Ahead-Of-Time) aggregation.

Question: What is Data Binding? What number of ways it tends to be finished?

Answer: In request to interface application information with the DOM (Data Object Model), information restricting is utilized. It occurs between the layout (HTML) and component (TypeScript). There are 3 different ways to accomplish information restricting:

Occasion Binding – Enables the application to react to client contribution to the objective climate

Property Binding – Enables insertion of qualities processed from application information into the HTML

Two-way Binding – Changes made in the application state gets naturally reflected in the view and the other way around. The ngModel mandate is utilized for accomplishing this kind of information restricting.

Question: Can you draw a correlation between the service() and the industrial factory() capacities?

Answer: Used for the business layer of the application, the service() work works as a constructor work. The capacity is conjured at runtime utilizing the new catchphrase.

Albeit the plant() work works in practically the same way as the service() work does, the previous is more adaptable and amazing. In genuine, the industrial factory() work are configuration designs that assistance in making objects.

Question: Please clarify the review cycle in Angular?

Answer: The way toward observing the watchlist to follow changes in the worth of the watch variable is named the summary cycle in Angular. The past and present forms of the extension model qualities are looked at in each overview cycle.

Albeit the condensation cycle measure gets set off certainly, it is feasible to begin it physically by utilizing the $apply() work.

Question: Could you clarify the different sorts of channels in AngularJS.

Answer: In request to organize the worth of articulation with the goal that it tends to be shown to the client, AngularJS has channels. It is feasible to add these channels to the regulators, orders, administrations, or formats. AngularJS likewise offers help for making custom channels.

Coordinating information in such a manner with the goal that it is shown just when certain models are satisfied is made conceivable utilizing channels. Channels are added to the articulations utilizing the line ‘|’ character. Different sorts of AngularJS channels are identified as follows:

money – Formats a number to the cash design

date – Formats an information to some particular arrangement

channel – Selects a subset of things from a cluster

json – Formats an item to a JSON string

limitTo – Limits a cluster or string into a predefined number of characters or components

lowercase – Formats a string to lowercase

number – Formats a number to a string

orderBy – Orders a cluster by an articulation

Question: What is new in Angular 6?

Answer: Here are a portion of the new angles presented in Angular 6:

Rakish Elements – It permits changing over Angular parts into web components and inserts something similar in some non-Angular application

Tree Shakeable Provider – Angular 6 presents another method of enlisting a supplier straightforwardly inside the @Injectable() decorator. It is accomplished by utilizing the providedIn trait

RxJS 6 – Angular 6 utilizes RxJS 6 inside

i18n (internationalization) – Without building the application once per region, any Angular application can have “runtime i18n”

How to Install Angular on Windows

Requirements :

How to Install Angular on Windows : To install Angular on your local machine , you need to follow this below :

1 NodeJS :

Angular will need an active LTS or maintenance LTS version of Node.js.

npm package manager :

Precise, the Angular CLI, and Angular applications rely upon npm bundles for some highlights and capacities. To download and introduce npm bundles, you need a npm bundle supervisor. This aide utilizes the npm customer order line interface, which is introduced with Node.js naturally. To watch that you have the npm customer introduced, run npm – v in a terminal window

Install the Angular CLI :

You utilize the Angular CLI to make projects, produce application and library code, and play out an assortment of progressing improvement undertakings like testing, packaging, and arrangement.

To introduce the Angular CLI, open a terminal window and run the accompanying order:

npm install -g @angular/cli

Create a workspace and initial application :

To create a new workspace and initial starter app:

Run the CLI order ng new and give the name my-application, as displayed here:

ng new my-application

The ng new order prompts you for data about highlights to remember for the underlying application. Acknowledge the defaults by squeezing the Enter or Return key.

The Angular CLI introduces the essential Angular npm bundles and different conditions. This can require a couple of moments.

The CLI makes another workspace and a basic Welcome application prepared to run.

Run the application :

The Angular CLI incorporates a worker, so you can assemble and serve your application locally.

Explore to the workspace organizer, for example, my-application.

Run the accompanying order:

cd my-app
ng serve --open

The ng serve order dispatches the worker, watches your documents, and revamps the application as you make changes to those records.

The – open (or just – o) alternative naturally opens your program to http://localhost:4200/.

On the off chance that your establishment and arrangement were effective, you should see a page like the accompanying.

 

How to Install Angular on Windows

How to Install Angular on Windows

This is how it looks

How to Add and Remove Row Dynamically in Angular with Validations

How to Add and Remove Row Dynamically in Angular with Validations

How to Add and Remove Row Dynamically in Angular with Validations :  Angular is an open-source, JavaScript system written in TypeScript. Google keeps up with it, and its main role is to foster single-page applications. As a system, Angular enjoys clear benefits while additionally giving a standard construction to engineers to work with. It empowers clients to make enormous applications in a viable way.

JavaScript is the most ordinarily utilized customer side prearranging language. It is composed into HTML reports to empower collaborations with website pages from various perspectives. As a generally simple to-learn language with inescapable help, it is appropriate to foster current applications.

However, is JavaScript ideal for creating single-page applications that require particularity, testability, and designer efficiency? Maybe not.

Requirments

Basic knowledge of Angular

Any Editor such as Visual Studio Code

External Library Added :

Bootstrap

FontAwesome

Introduction to the Blog

This tutorial will teach you how to add and remove rows from the grid.
This tutorial also covers the Reactive form validations on dynamically generated elements and reset form after submitting the form.

After Researching many things over google about this functionality the blogs were not covering all things at once.

So I decided to write code myself and share it with everyone who really needs it.

Let’s start :

It will require 3 Files.

app.component.html

app.component.ts

style.css (to import FontAwesome and Bootstrap library ).


.app.component.html

<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Dynamic Add and Remove Rows</h4>
<form [formGroup]="requestCreateForm" (ngSubmit)="submit()" class="row">
<div class="col-lg-12">
<hr>
<!--  Just a Divider Line -->
</div>
<div class="col-lg-12" formArrayName="itemRows">
<div class="row" *ngFor="let itemrow of itemRowsControls; let i=index" [formGroupName]="i">
<label class="col-lg-1 col-form-label">Currency
<span class="text-danger">*</span>
</label>
<div class="col-lg-2">
<select class="form-control" formControlName="currency" [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'currency')?.errors}">
<option value="">Select</option>                                      
<option value="INR ">INR</option>
<option value="Doller ">DOLLER</option>
</select>

<div *ngIf="submitted && itemrow.get( 'currency')?.errors " class="invalid-feedback ">
<div *ngIf="submitted && itemrow.get( 'currency')?.errors?.required ">
Currency is required.
</div>
</div>
</div>
<label for="amt-input " class="col-lg-1 col-form-label ">Amount <span class="text-danger ">*</span>
</label>
<div class="col-md-2 pr-0 mb-3 ">
<input class="form-control" formControlName="amount" type="text " id="amt-input " [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'amount')?.errors}" />
<div *ngIf="submitted && itemrow.get( 'amount')?.errors" class="invalid-feedback ">
<div *ngIf="submitted && itemrow.get( 'amount')?.errors?.required">
Amount is required.
</div>
<div *ngIf="submitted && itemrow.get('amount')?.hasError( 'maxlength') ">
Amount can not exceed 10 characters in length.
</div>
<div *ngIf="submitted && itemrow.get('amount')?.errors?.pattern">
Amount Number must be number
</div>
</div>
</div>
<div class="col-lg-2 ">
<label class="col-form-label ">Currency Type<span class="text-danger ">*</span></label>
</div>
<div class="col-md-2 pr-0 mb-3 ">
<select class="form-control " formControlName="currencyType" [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'currencyType')?.errors}">
<option value=" ">Select</option>
<option value="Fake ">Fake </option>
<option value="Original ">Original</option>
</select>
<div *ngIf="submitted && itemrow.get('currencyType')?.errors" class="invalid-feedback">
<div *ngIf="submitted && itemrow.get('currencyType')?.errors?.required">
Type is required.
</div>
</div>
</div>
<div class="col-lg-2 text-right">
<button type="button" (click)="addNewRow()" class="btn btn-primary mr-2"><i class="fa fa-plus-circle"
aria-hidden="true"></i></button>
<button type="button" (click)="deleteRow(i)" class="btn btn-outline-danger ml-2"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="col-lg-12">
<hr>
</div>
<div class="col-lg-12 text-center mt-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<!-- end col -->
</div>
<!-- end row -->
</div>

 


.app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from "@angular/forms";
import { Router } from "@angular/router";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
submitted = false;
requestCreateForm: FormGroup;
TotalRow : number;
constructor(private formBuilder: FormBuilder,private router: Router,) { }
get f(){
return this.requestCreateForm.controls;
}
get t() { return this.f.itemRows as FormArray; }
get itemRowsControls() { return (<FormArray>this.requestCreateForm.get('itemRows')).controls; }
ngOnInit(): void {
this.requestCreateForm = this.formBuilder.group({
itemRows: this.formBuilder.array([this.initItemRows()]),      
});     
}
initItemRows() {
return this.formBuilder.group({
currency: ['', Validators.compose([Validators.required])],
amount: ['', Validators.compose([Validators.required,  Validators.pattern("^[0-9]*$"),Validators.maxLength(10)])],
currencyType: ['', Validators.compose([Validators.required])],
});
}
addNewRow() {     
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
if(control.length <= 4){        
control.push(this.initItemRows());    
}
else{
alert('Sorry !! You can only add 5 Rows');
}

}
deleteRow(index: number) {
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
if(control != null){
this.TotalRow = control.value.length ;
}
if(this.TotalRow > 1){
control.removeAt(index);
}    
else{
alert('Last Row can not be deleted');
}

}  
emptyArray(){
// Removing all valus from array expect [0] index ; 
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
this.TotalRow = control.value.length  - 1;
for (let i = this.TotalRow - 1; i >= 0; i--){
control.removeAt(i);
}   
}
submit(){
this.submitted = true;
console.log('This is formdata-->', this.requestCreateForm.value);
if (this.requestCreateForm.invalid) {
alert('Form is not Valid Now');
return;
}
else{
alert('A Valid Form');
this.submitted = false; 
this.requestCreateForm.reset();
this.t.reset(); 
}

}
}

 


style.css

@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~font-awesome/css/font-awesome.css";

 

To clone this project

git clone https://github.com/rohitgautam-mobi/Add-and-Remove-Row-Dynamically-in-Angular-with-Validations.git

 

That is all for this blog

Thanks 🙂

Happy Coding