Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer : After collecting questions from many interviews. I came to search for those answer which is needed for the interviews question. These questions are very interesting which covers mostly HTML, CSS/ JavaScript, and jQuery, and Experience a couple of years. This is going to be very useful before anyone faces any interview.

 

In CSS when will you use a CSS float?

Ans –  The “float” CSS property specifies that an element should be placed along the left or right side of its container, where text and inline elements will wrap around it.

Q2 – While writing an error message what are all things do you need to take into consideration?

Ans –  Be Clear And Not Ambiguous

Be Short And Meaningful

Be Humble

Be Specific And Relevant

Don’t Use Technical Jargons.

Avoid Negative Words

Avoid Uppercase Text.

Give Direction to User

Explain what a Grid System is?

Ans –  There is nothing worse for an artist than a blank canvas. A grid system is a set of measurements a graphic designer can use to align and size objects within the given format. Although there are a few different categories of grid systems, there are no strict rules on what can or cannot be a grid. It’s up to you. Any guides that help you shape the final design are okay.

Q4 – What does is NaN Function do?

Answer –  The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value equates to NaN. Otherwise, it returns false.

isNaN(123) //false

isNaN(-1.23) //false

isNaN(52) //false

isNaN(0) //false

isNaN(‘123’) //false

isNaN(‘Hello’) //true

isNaN(‘2005/12/12’) //true

isNaN() //false

isNaN(true) //false

isNaN(undefined) //true

isNaN(‘NaN’) //true

isNaN(NaN) //true

Explain What is Information Architecture?

Answer –  Information architecture (IA) is the structural design of shared information environments; the art and science of organizing and labelling websites, intranets, online communities and software to support usability and findability; and an emerging community of practice focused on bringing principles of design, architecture and information science to the digital landscape.

What is the difference between span & Div?

Answer –  The primary difference between a div and a span is their default behavior. By default, a <div> is a block-level-element and a <span> is an inline element. In other words, if you want to adjust a small portion of text and not break it out of the current line, you should use a <span>. If you need to modify a large division, the height, move an element, or contain other elements, you should use a <div>.

What is Mobile-First Design ?.

Answer – Responsive design starts on the desktop; that is, at the maximum required resolution, and then scales down to the smallest screen. Even though the content and layout contract to fit smartphones, the navigation, content, and download speeds are geared more for your traditional website.

Mobile-first design is similar to designing a mobile app and then adapting the layout that it can be viewed neatly on tablet and desktop devices without too many modifications. Your whole design and layout are based on providing an excellent mobile user experience: fast download speeds, rich media content to keep your target audience interested, easy touchscreen navigation, and so on.

WHY MOBILE-FIRST DESIGN

Responsive design sounds good, we hear you say. Why should you risk a mobile-first design? Quite simply, the stats show that we have become addicted to surfing on mobile devices. Currently, 52.64% of the total traffic on the Internet is done via mobile phones, and by the end of the year experts from Zenith Media predict an increase of up to 75%. With this information in mind, it is essential to understand what mobile-first design is and what its benefits are. Unlike responsive design, mobile-first is about a complete mobile user experience: adapted app-like user interface, less text, larger fonts, fast download speed, video and audio, one call-to-action per page, short forms, etcetera. Additionally, mobile browsers shortly will have access to more of the smartphone features like camera, haptic feedback, voice detection, so that a mobile-first design will be able to provide a unique experience to put your site ahead of the competition and drive traffic.

Difference between bootstrap3 and bootstrap 4?

Answer – Bootstrap 3 Source CSS Files is LESS.

Bootstrap 4 Source CSS files Converted in SCSS. 

Bootstrap 3 has 4 grid system (col-xs-3, col-sm-3, col-md-3, col-lg-3).

Bootstrap 4 has 5 grid system (.col-, .col-sm-3, .col-md-3, .col-lg-3, .col-xl-3). Bootstrap 4 has removed the xs from the lowest break point. Therefore, (col-) covers all devices. 

Bootstrap 3 Offset class is like this (col-md-offset-4).

Bootstrap 4 has changed the offset class (offset-md-4). 

In Bootstrap 3 we are used this (.img-responsive) class for the responsive images.

Bootstrap 4 has changed the class for responsive image (.img-fluid). 

In Bootstrap 3 we are used (.input-lg) and (.input-sm) to increase and decrease the input size.

Bootstrap 4 has changed to (.form-control-lg) and (.form-control-sm) to increase and decrease the input size.

What is the difference between Body.Onload() & document.ready() ?

Answer- The main differences between the two are:

  1. Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery’s document.ready() event will be called once the DOM is loaded i.e., it won’t wait for the resources like images to get loaded. Hence, the functions in jQuery’s ready event will get executed once the HTML structure is loaded without waiting for the resources.
  2. We can have multiple document.ready() in a page but Body.Onload() event cannot.

What are the Different JavaScript Types?

Answer- In JavaScript, there are two different kinds of data: primitives, and objects. A primitive is simply a data type that is not an object and has no methods.

In JS, there are six primitive data types:

BUNNSS

Boolean, Undefined,  Number, Null, String, Symbol

What about Objects?

Objects are not a primitive dataType.

An object is a collection of properties. These properties are stored in key/value pairs. Properties can reference any type of data, including objects and/or primitive values.

What is the prompt box?

Answer – The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page.

Note: When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.

The prompt() method returns the input value if the user clicks “OK”. If the user clicks “cancel” the method returns null.

What is the difference between HTML & HTML5?

Ans – The biggest advantage that HTML5 has over its unnumbered predecessor is that it has high-level audio and video support which was not a part of the version specifications in the previous HTML. Other differences between HTML and HTML5:

SVG, canvas and other virtual vector graphics are supported in HTML5, whereas in HTML, using vector graphics was only possible by using it in conjunction with different technologies like Flash, VML, and Silver-light, etc.

HTML5 uses web SQL databases, application cache for temporary storing data, meanwhile, in HTML, only browser cache could be utilized for this purpose.

Another difference between HTML and HTML5 worth mentioning is that the former doesn’t allow JavaScript to run within the web browser (it instead runs in the browser interface thread) whereas the latter provides full support for JavaScript to run in the background (This is a possible courtesy to the JS web worker API of HTML5).

HTML5 is not based on SGML, and that allows it to have improved parsing rules which provide enhanced compatibility.

In HTML5, inline MathML and SVG can be used in text whereas this wasn’t possible in HTML.

Some of the deprecated elements that have now been dropped completely are index, no frames, acronym, applet, basefont, dir, font, frame, frameset, big, center, strike, tt.

HTML5 supports new kinds of form controls, for example, dates and times, email, number, range, tel, url, search, etc.

There are many new elements introduced in HTML. Some of the most important ones are: summary, time, aside, audio, command, data, data list, details, embed, wbr, figcaption, figure, footer, header, article, hgroup, bdi, canvas, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, track, video.

What is $() in the jQuery library? 

Answer – The $() function is an alias of jQuery() function, at first it looks weird and makes jQuery code cryptic, but once you get used to it, you will love its brevity. $() function is used to wrap any object into a jQuery object, which then allows you to call various method-defined jQuery objects. You can even pass a selector string to the $()function, and it will return a jQuery object containing an array of all matched DOM elements. I have seen this jQuery asked several times, despite it’s quite basic, it is used to differentiate between developers who know jQuery or not.

https://career.guru99.com/top-50-jquery-interview-questions/

https://www.codeproject.com/Articles/620811/Latest-JavaScript-Interview-Questions-and-Answers

 What is Grouping?

Answer – When more than one selector shares the same declaration, they may be grouped together via a comma-separated list; this allows you to reduce the size of the CSS (every bit and byte is important) and makes it more readable. The following snippet applies the same background to the first three heading elements.h1, h2, h3 {background: red;}

What is “Semantic Element”?

Ans – A semantic element clearly describes its meaning to both the browser and the developer.

Examples of non-semantic elements: <div> and <span> – Tells nothing about its content.

Examples of semantic elements: <form>, <table>, and <article> – Clearly defines its content.

Which command will give you a version of Jquery”?

Ans – The command $.ui.version returns jQuery UI version.

What is event bubbling?

Event bubbling is a term you might have come across on your JavaScript travels. It relates to the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example).

Why do we use metatag?

The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page but will be machine parsable.

Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.

The metadata can be used by browsers (how to display content or reload the page), search engines (keywords), or other web services.

What is a web worker?

Ans- When executing scripts on an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

What are webhooks?

Webhooks provide a mechanism whereby a server-side application can notify a client-side application when a new event (that the client-side application might be interested in) has occurred on the server. Webhooks operate on the concept of “event reaction” (don’t call me, I’ll call you if I have something new), and thus avoids the need for constant polling of the server-side application by the client-side application. Thus, rather than the client-side application constantly polling the server-side application to check for new events, the server-side application calls the client-side application (by invoking a client-provided webhook URL) anytime the server-side has something new to report to the client.

This is the core concept of the Webhook.

What is DOCTYPE!?

The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag.

The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.

In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language so that the browsers render the content correctly.

HTML5 is not based on SGML and therefore does not require a reference to a DTD.

Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.

What is the Callback Function? 

Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

Is JavaScript case sensitive?

Ans: Yes!

A function getElementById is not the same as getElementbyID.

 What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

What is the ‘this’ keyword in JavaScript?

‘This’ keyword refers to the object from where it was called.

What is closure in JavaScript?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Lexical scoping

Consider the following example code:

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

What is Hoisting in JavaScript?

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Days Counter Script

Days Counter Script

Days Counter Script

Days Counter Script : On the off chance that you’ve at any point considered the number of days are remaining from the date of launch, this content will reveal to you that. It very well may be adjusted to work with anytime, if not every one of them together!

We can show a days count script showing time left from an occasion. Let’s assume we are running a mission which will end following two days. Here we will show a counter saying days , hours , minutes and seconds left for the occasion to occur or the mission to end. This content uses the setTimeout work similarly as it is utilized in showing a changing clock script. Here this setTimeout script triggers another capacity in each 1000 factory seconds ( or in 1 sec ).

This content uses customer side JavaScript to produce the check down clock. The underlying worth in number of seconds left for the commencement to end will be passed to the capacity. At the hour of page stacking the seconds left ( a numeric worth ) is gathered and in light of this worth the days , hours, minutes and seconds are determined and shown.

Yon also check the days between two dates :

Days Calculator between two dates / JavaScript

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Days Counter</title>
</head>
<body>
    <div class="container">
        <div class="calendar">
            <div class="daysRemaining">
                Number of Days Remaining.
            </div>
            <div class="result" id="demo">

            </div>
        </div>

    </div>
</body>
</html>

CSS

.calendar {
            width: 99%;
            font-size: 50px;
            font-family: -webkit-pictograph;
            display: flex;
            justify-content: center;
            height: 90vh;
            align-items: center;
            border: 5px solid #b8ce9b;
            background-color: #d4efb1;
            flex-direction: column;
        }
        
        .daysRemaining {
            font-size: 15px;
        }

JavaScript

 // Set the date we're counting down to
 var countDownDate = new Date("Nov 24, 2021 09:00:00").getTime();
 // Update the count down every 1 second
 var x = setInterval(function() {
     // Get todays date and time
     var now = new Date().getTime();
     // Find the distance between now an the count down date
     var distance = countDownDate - now;

     // Time calculations for days, hours, minutes and seconds
     var days = Math.floor(distance / (1000 * 60 * 60 * 24));
     var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
     var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
     var seconds = Math.floor((distance % (1000 * 60)) / 1000);

     // Display the result in the element with id="demo"
     document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
         minutes + "m " + seconds + "s ";

     // If the count down is finished, write some text 
     if (distance < 0) {
         clearInterval(x);
         document.getElementById("demo").innerHTML = "EXPIRED";
     }
 }, 1000);

Like us on Facebook – Online Portfolio

Days Calculator between two dates / JavaScript

Days Calculator between two dates / JavaScript

Days Calculator between the dates: The apparatus on this page is utilized to ascertain the time distinction between the two dates. The outcome given incorporates data about how long, months are between the given dates. Also, precisely how long, months, and days there are.

Utilizing this day’s number cruncher is exceptionally simple. Enter two dates from and to in the structure fields (Start date and End date). The dates ought to be entered in the accompanying configuration: DD/MM/YYYY (for example 01/11/2020). In the wake of tapping on any of the structure handles, a schedule will show up, which will make it simpler to choose the proper day. Obviously, the date can likewise be entered utilizing the console.

 

Live Demo

 

Custom Dropdown
FROM TO
Days Remaining
00:00:00

How to use a calculator?

The day’s number cruncher permits you to compute precisely how old you are. You can see precisely how long you as of now have. The age given in days is frequently utilized when discussing infants.

You can check how long are left until an occasion (for example a birthday).

 

Example

 

In the wake of entering in the field Start date the date 01/11/2020 and in the field End date the date 25/07/2021, the outcome will be gotten:

The contrast between the dates is:

265d days

(this is how long, months, and days I have when I make this page ;))

How to check how long are left until your birthday? You should simply enter the present date in the field Start date and your next birthday in the field End date. This way you will know precisely how long your birthday will be in.

On Facebook 

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Days Calculator
    </title>
  </head>
  <body>
    <div class="container">
      <div class="result">
        <div class="calendar">
          FROM 
          <input type="date" id="fromDate"> TO 
          <input type="date" id="toDate">
          <button id="calculate" onclick="calculateNow();">Calculate Now
          </button>
        </div>
        <div class="NumberOfDaysRemaining">
          Days Remaining
        </div>
        <div class="time" id="demo">
          00:00:00
        </div>
      </div>
    </div>
  </body>
</html>

 

CSS

 .result {
            width: 99%;
            font-size: 50px;
            font-family: -webkit-pictograph;
            display: flex;
            justify-content: center;
            height: 90vh;
            align-items: center;
            border: 5px solid grey;
            background-color: #ecd2d2;
            flex-direction: column;
        }
        
        .calendar {
            font-size: 15px;
            text-align:center
        }

 

Javascript

const calculateNow = () => {
    let currentDate = new Date();
    let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
    let toDate = document.getElementById('toDate').value;
    let fromDate = document.getElementById('fromDate').value + ' ' + time;
    if (toDate != '' && fromDate != '' && fromDate <= toDate) {
        document.getElementById("demo").innerHTML = "";
        let countDownDate = new Date(toDate).getTime();
        // Get todays date and time
        let now = new Date(fromDate).getTime();
        // Find the distance between now an the count down date
        let distance = countDownDate - now;
        // Time calculations for days, hours, minutes and seconds
        let days = Math.floor(distance / (1000 * 60 * 60 * 24));
        let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Display the result in the element with id="demo"
        document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
            minutes + "m " + seconds + "s ";

        // If the count down is finished, write some text 
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }
    } else {
        alert('From Date and To Date Should be Valid');
    }
}

You can also see realted post

here

Seat Reservation with JavaScript

Seat Reservation with JavaScript

Seat Reservation with JavaScript : In this article I will show, How to implement seat booking with Pure JavaScript. Thus, I chose to compose on it. This post discloses how to execute seat booking with JavaScript . It tends to be utilized in online Bus, flight, inn, test backing, film and ticket booking framework.

A confounding variable about train travel in an unfamiliar nation is realizing what is important and what isn’t. This is particularly the situation with seat bookings for trains. For certain tickets you need to have a booking and with others it’s basically unrealistic. Thus we need to clear these things up for you, so you can travel like a neighborhood.

To put it plainly, a seating reservation implies you get a seat which is alloted to you by and by. Actually like a seat on an aircraft. Pulling up a chair reservation can be awesome thing yet not generally fundamental or conceivable. How might you know whether you need a booking or then again in case it is even conceivable to have one? First and foremost you need to figure out what sort of train you will be on.

 

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Practice</title>
</head>
<body>
    <div class="bus">
        <div id="selectedseataDisplay">
        </div>
        <div class="inner">
            <div class="leftside">
                <div id="s1" class="seat1"></div>
                <div id="s2" class="seat2"></div>
                <div id="s3" class="seat3"></div>
                <div id="s4" class="seat4"></div>
                <div id="s5" class="seat5"></div>
                <div id="s6" class="seat6"></div>
                <div id="s7" class="seat7"></div>
                <div id="s8" class="seat8"></div>
                <div id="s9" class="seat9"></div>
                <div id="s10" class="seat10"></div>
            </div>
            <div class="rightside">
                <div id="s11" class="seat11"></div>
                <div id="s12" class="seat12"></div>
                <div id="s13" class="seat13"></div>
                <div id="s14" class="seat14"></div>
                <div id="s15" class="seat15"></div>
                <div id="s16" class="seat16"></div>
                <div id="s17" class="seat17"></div>
                <div id="s18" class="seat18"></div>
                <div id="s19" class="seat19"></div>
                <div id="s20" class="seat20"></div>
            </div>
        </div>
    </div>
</body>
</html>

 

CSS

 .bus {
        display: flex;
        justify-content: center;
    }

    .inner {
        display: flex;
        justify-content: space-between;
        width: 700px;
    }

    .rightside {
        margin-left: 20px;
    }

    .leftside,
    .rightside {
        display: flex;
        flex-wrap: wrap;
    }

    .leftside div,
    .rightside div {
        width: 100px;
        height: 100px;
        background-color: rebeccapurple;
        border-top-left-radius: 30px;
        border-top-right-radius: 30px;
        margin-top: 15px;
        margin-left: 10px;
        cursor: pointer;
        border: 5px solid #d4a8ff;
    }

    .leftside div:hover,
    .rightside div:hover {
        background-color: #d4a8ff;
        border: 5px solid rebeccapurple;
    }

    .selected,
    .selected:hover {
        background-color: #7ace7d !important;
        border: 5px solid #37a262 !important;
    }
    #selectedseataDisplay{
        display: flex;
    flex-wrap: wrap;
    width: 200px;
    height: 200px;
    margin-top: 20px;
    }
    #selectedseataDisplay li{
    background-color: #7ace7d;
    color: #fff;
    text-transform: capitalize;
    font-size: 14px;
    font-weight: bold;
    font-family: monospace;
    padding: 5px;
    list-style: none;
    height: 35px;
    width: 60px;
    margin-right: 5px;
    border: 2px solid #37a262;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    text-align: center;
    margin-bottom:5px;
    }

JavaScript

 const selectedSeat = [];
    document.addEventListener('click', function (e) {
        e = e || window.event;
        const target = e.target || e.srcElement,
            text = target.className;
        let seatNumber = text;
        document.getElementsByClassName(seatNumber)[0].classList.toggle('selected');
        textID = target.id;
        if (document.getElementById(textID).classList.contains("selected")) {
            selectedSeat.push(text);
        }
        else {
            let seatTo = text.split(" ");
            let seatToRemove = seatTo[0];
            for (let i = 0; i < selectedSeat.length; i++) {
                if (selectedSeat[i] === seatToRemove) {
                    selectedSeat.splice(i, 1);
                }
            }
        }
        console.log('selectedSeat are ', selectedSeat);
        document.getElementById('selectedseataDisplay').innerHTML = '';
        for(let j=0; j<selectedSeat.length;j++){
                        document.getElementById('selectedseataDisplay').innerHTML += "<li>"+selectedSeat[j]+"</li>";
        }

    }, false);

Live Demo

See the Pen Seat Reservation with JavaScript by Rohit Gautam (@TheRrohitt) on CodePen.

Setup React App

Create React App

Setup React App

Setup React App

Setup React App : is an agreeable climate for learning React and is the most ideal approach to begin assembling another single-page application in React.

ReactJS is a declarativeefficient, and flexible JavaScript library for building reusable UI components. It is an open-source, component-based front end library which is responsible only for the view layer of the application. It was initially developed and maintained by Facebook and later used in its products like WhatsApp & Instagram.

Respond makes it effortless to make intuitive UIs. Plan straightforward perspectives for each state in your application, and React will effectively refresh and deliver the perfect segments when your information changes.

Explanatory perspectives make your code more unsurprising and simpler to investigate

 

It sets up your advancement climate with the goal that you can utilize the most recent JavaScript highlights, gives a pleasant designer experience, and enhances your application for creation. You’ll have to have Node >= 10.16 and npm >= 5.6 on your machine. To make an undertaking, run:

 

 

npm create-react-app my-application
cd my-application
npm start

 

Make React App doesn’t deal with backend rationale or data sets; it simply makes a frontend construct pipeline, so you can utilize it with any backend you need. In the engine, it utilizes Babel and webpack, however you don’t have to know anything about them.

You can study Create React App from its README and the User Guide.

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