Exploring the method of dynamically adding a row to a table on button click using Angular 2

In the midst of my Angular2 project, I am exploring the possibility of dynamically adding rows to a table when a button is clicked. While I am aware that *ngFor can achieve this, I am curious if it can be implemented only upon the clicking of a button.

Answer №1

Typically, the *ngFor directive is used to loop through an array, usually containing objects. If your array is named "data," you can implement it like this:

<table *ngIf="data.length">  <!--Only display if there is data-->
<tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
</tr>
<tr *ngFor="let item of data">
   <td>{{item.firstName}}</td>
   <td>{{item.lastName}}</td>
   <td>{{item.age}}</td>
</tr>
</table>

Make sure to define the data variable like this:

data:any[]=[] //don't forget to initialize it!

A button can trigger something like:

onClick()
{
   this.data.push({firstName:"First Name", lastName:"Last Name", age:18})
}

Answer №2

Just a brief example:

  <button (onClick)="toggle=!toggle">click</button>
       <div *ngIf="toggle">
        <div *ngFor="...">
         ...
        </div>
       </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficient methods to transfer values or arrays between components in Angular 8 without relying on local storage

I am working on a project that involves two components: a login component and a home component. I need to pass user data from the login component to the home component without using local storage. Is there a way to achieve this in Angular 8? Below is the ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

I discovered an issue in Handsontable while trying to copy and paste a numeric value in German format

For my upcoming project, I am looking to incorporate the Handsontable JavaScript grid framework. However, I have encountered a small bug that is hindering me from utilizing this library to its fullest potential. The task at hand involves displaying a tabl ...

Error message indicating the Ionic 5 Phonegap-NFC plugin is not installed, even though it has been successfully installed

While utilizing the NFC library, I followed the Ionic documentation recommendations at (https://github.com/chariotsolutions/phonegap-nfc) and (https://ionicframework.com/docs/native/nfc). However, when trying to access the code in my component that calls ...

Creating a fresh React component within a current project: What steps can I take to view it on the browser?

My React project is quite complex, built using create-react-app and utilizing react-scripts to run the development server. I am looking to develop a new React component that will allow users to input structured data, complete with list additions, dropdown ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

There is no record of the property's history

I am embarking on a fresh project utilizing React and TypeScript. One of the hurdles I have encountered is with the Router. Strangely, TypeScript does not recognize the history property, even though it should be accessible as mentioned in the documentation ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Is the Facebook AJAX Permissions Dialog displayed outside of a Pop-Up?

I have conducted extensive research but have failed to find a clear answer to my query. Although there is plentiful information on Facebook API AJAX/PHP communication, I am unable to locate an example where the Permission Dialog for an app (showPermissionD ...

Sending properties to MUI Box component enhancer (Typescript)

I'm having trouble figuring out how to pass props to override the Box component. I specifically need to pass position="end" as InputAdornment requires it, but I can't seem to find the proper way in the documentation. Here's the complete co ...

Is it possible to further simplify this piece of JavaScript using jQuery?

In my journey to learn and grow with Javascript, I have come across a snippet of code that simply attaches an onclick event to a button and updates the text of an em tag below it. As I delve deeper into jQuery, I am beginning to appreciate its syntax and u ...

Encountered an issue while saving a blob in NativeScript: "Unable to convert object to [B at index

I have a Nativescript Angular application that is downloading a PDF from a Rails server in Blob Uint8Array format. When I attempt to save it, I encounter the following error: JS: /data/user/0/com.asset.management/files/result.pdf JS: ERROR Error: Uncaught ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...

What is the best way to send two Array objects through http requests in AngularJS?

Is there a way to receive two parameters as an array in an HTTP action, like List `abc` and List `xyz`, and then use a model class? public class ItemAndChecque { public List<SaleItem> saleitem { get; set; } public List<itemChecqe> item ...

Using jQuery to detect changes in the value of form fields, excluding any changes related to display toggles

Currently, I am in the process of revamping a large form that includes various input fields and dropdown menus. The goal is to submit it via AJAX once a field loses focus but only if the value has been altered. To achieve this, I have set up a jQuery selec ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

Adding associated documents into MongoDB from an Express application

My mongo db schema is structured as follows: users: {username:"", age: "", data: [ {field1:"", field2:""}, {field1:"", field2:""} ] } I am facing an issue with sending my user object to my express route for posting data to the database. ...