The FormGroup Matrix in Angular 2+

Looking to develop an interface for creating a matrix, which requires two inputs for width and height. The matrix of inputs will vary based on these dimensions.

I'm facing a challenge in making these inputs unique so they can be correctly associated with the matrix in the class.

Anyone have a solution for creating a two-way data-bound matrix? Any tips would be appreciated as well.

I started working with FormGroup but then came across FormArray. However, I couldn't find anything like FormMatrix, which is unfortunate.

Here's a snippet of the HTML code:

<p *ngFor="let itemX of createArrayAndFill(thirdData.x);">
    <mat-form-field *ngFor="let itemY of createArrayAndFill(thirdData.y);">
        <input [(ngModel)]="thirdData.matrix[itemX][itemY]" matInput name="item--{{itemX}}--{{itemY}}"
            placeholder="Value {{itemX}} {{itemY}}" formControlName="matrixControl">
    </mat-form-field>
</p>

Incorporating some JavaScript logic into the mix:

createArrayAndFill(n: number) {
    return Array(n).fill(0).map((item, i) => i)
}
thirdData = {
    x: 3, y: 3, matrix: [[1.1, 0.8, 0.9],
    [6.1, 3.2, 0.4],
    [-0.4, 0.2, 8.7]]
}

This setup is built using Angular version 7.

Answer №1

To navigate the table using arrow keys, you can check out the code on StackBlitz. Additionally, for more information on creating dynamic columns and rows in an Angular 6 HTML table, refer to this Stack Overflow answer.

Here is the TypeScript code:

rows=5;
cols=3;
form=new FormArray([]);

ngOnInit()
{
  for (let i = 0; i < this.rows; i++) {
      this.form.push(new FormArray([]))
      for (let j = 0; j < this.cols; j++) {
        (this.form.at(i) as FormArray).push(new FormControl())
      }
  }
}

And here is the corresponding HTML code:

<form [formGroup]="form">
  <div *ngFor="let row of form.controls;let i=index">
    <input *ngFor="let col of row.controls" [formControl]="col">
  </div>
</form>

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

Insufficient html content causing empty spaces on the page

Having trouble with my HTML layout - I want a main content area centered on the page with a sidebar that slides out from the left. Everything is working except for a large gap on the left side. How can I move my content to the left to fill the entire page ...

Obtain information from a web address using Ionic framework

Hello, I am experiencing an issue with retrieving data from a URL in my Ionic application. When using @angular/http to fetch a JSON object from the URL, everything works fine in the browser when running 'ionic serve'. However, when deploying the ...

Should beginner node.js developers start with NestJs or should they gain experience with Express first?

After completing a project using the Express JS library on the Mozilla (MDN) training site, I started looking for a more reliable option due to various reasons such as architectural concerns and issues with modern JavaScript features like async-await. That ...

Tips for registering a provider in Angular 2 using dynamic data during runtime

Previously in Beta, I was able to achieve the following: export class AppBootstrapper { constructor(mySettings: AppSettings) { bootstrap(App, [ provide(AppSettings, { useFactory: () => mySettings }) ] } ...

Using NPM in combination with React and TypeScript to incorporate AMD modules

I am currently in the process of setting up a development environment for an application that is written in TypeScript using React. I already have existing TypeScript code that compiles to ES5 and AMD modules. My goal is to avoid any JavaScript transpilat ...

What is the most effective strategy for handling JSON responses in Angular's Front End when subscribing to them using a forkJoin?

After researching various solutions for handling JSON mapping issues in the front end, I still haven't found a satisfactory answer. Despite trying different approaches, such as working with Root-object and nested interfaces, I'm struggling to map ...

Setting the status code in Angular 6 Server Side Rendering (SSR) from a Component

Is it possible to customize status codes like 404, 401, and 500 as needed? I am currently working with Angular 6 and have come across outdated tutorials that do not provide solutions that work. These tutorials often refer to a server.ts file that is no lo ...

The Ionic mobile application fails to show any content on the screen

After following a tutorial by Josh Moroney on "Building a Review app with Ionic 2, MongoDB, and Node", I created a basic ionic app. However, when I run the app using the `ionic serve` command, it loads in the browser without any errors but displays a compl ...

NX nest application: accessing environment variables from the distribution directory

I've organized my project structure like this: https://i.sstatic.net/WRKCI.png Using nx with nest. In the app.module.ts file, I've set up the ConfigModule to read the .env file based on the NODE_ENV variable, which is then used to connect to Mo ...

What is the best way to assign ngModel to dynamically inserted input rows in Angular 4+ (specifically in a mat-table)?

Just a quick question - how can I add ngModel to dynamically added new input rows? I have a Mat table with multiple rows and an "add element" method that adds a new row every time a button is clicked. This way, I want to bind the user-entered values and se ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

What is the optimal location for storing a chosen collection of items?

There are multiple lists of elements available: let list1 = [1,2,3,4]; let list2 = [1,2,3,4]; let list3 = [1,2,3,4]; Each list is being iterated through in a loop: <div *ngFor="let el of list1" (click)="set(el)">{{el}</div> <div *ngFor= ...

Angular2: Implementing regular updates to a large number of rows based on a set time

I am currently facing an issue with updating a large number of rows (approximately 2000) every 1 or 2 seconds. While I have a solution in place, my browser sometimes hangs while executing it. One specific problem with the current solution is that the "up ...

Guide on inserting a date into a MySQL DATETIME column in Angular with Node.js

In my application, I have a date picker component. My goal is to store the selected date in a MySQL database column with the data type of DATETIME. When using Angular, the value retrieved from the date picker is displayed as such: console.log(date.value): ...

Incorporating a polling feature into an HTTP request within Angular 8

How can I implement a polling mechanism in order to fetch the status of a job (type Status) every minute for a service that requests this object with a specific JOB_ID as an argument? retrieveJobStatus$(JOB_ID): Observable<Status> { const url = ...

angular2 ngFor is not functioning properly

I'm having an issue where I cannot get textboxes to appear whenever a user clicks a button. I am attempting to achieve this using ngFor, but for some reason, the ngFor is not iterating as expected. Even after trying to change the array reference with ...

Why won't angular ng update work? Is there a timeout issue with the proxy settings?

I am encountering a problem with my angular project. When I am at work, I use a proxy, but when I am at home, I do not. So I added the following: npm config set https-proxy http://xx.xx.xx.xx:9090 npm config set proxy http://xx.xx.xx.xx:9090 and it works ...

Error in ng2-translate: TranslatePipe.transform cannot access the property 'subscribe' as it is undefined

I have been utilizing ng2-translate within my Angular 5 project and I am currently in the process of setting up a unit test for a specific component. Typically, I import TranslateModule.forRoot( *...* ) in my Tests and everything runs smoothly when using t ...

The sendKeys function in Selenium seems to be missing some characters when inputting text

Currently, I am working on test automation using Java, Selenium, and Chrome. Our developers recently made an upgrade from AngularJS to Angular2 for our UI. Ever since the upgrade, I've been facing an issue where sendKeys is inputting incomplete charac ...

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...