Transfer the data for 'keys' and 'input text' from *ngFor to the .ts file

I am facing difficulty in creating a string with dynamically generated keys from *ngFor and user input text. Let me provide some code to better explain my need.

<th *ngFor="let column of Filter" >
    <tr>{{ column.name }}: <input type="{{column.type}}" id="{{ column.key }}" name="{{ column.key }}" autocomplete="off"  > &nbsp;</tr>
</th>
<button class="btn btn-success" type="submit" (click)="fFilter(string)">Search</button>

The desired string should be: "column.key1='input1', column.key2='input2' ..." for all columns.

I have been searching for a solution, but none has proved helpful so far. How can I achieve this? Apologies for not articulating my issue clearly.

Answer №1

After carefully analyzing your needs, I have developed a suitable solution for you.

From what I gather, you have user controls (as depicted in the image below) generated using the code snippet provided here:

<th *ngFor="let column of Filter" >
      <tr>{{ column.name }}: 
      <input type="{{column.type}}" id="{{ column.key }}" 
             name="{{ column.key }}" autocomplete="off" 
            [(ngModel)]="column.value" > &nbsp;</tr>
    </th>
    <hr>
    <button class="btn btn-success" type="submit" (click)="fFilter()">Search</button>

https://i.sstatic.net/3yo4J.png https://i.sstatic.net/MjMLU.png Once data is entered into all textboxes, when the user clicks "Search," you wish to display the output or data as shown in the alert message in the image below within the function call. https://i.sstatic.net/YjSNJ.png

I have included [(ngModel)]="column.value" for two-way binding of each textbox's data. This allows us to retrieve this data in the .ts file.

Column.model.ts:

export class Column{
   public key:string;
   public type:string;
   public name:string;
   public value:string;
    constructor(key:string,type:string,name:string,value:string)
    {
        this.key=key;
        this.type=type;
        this.name=name;
        this.value=value;
    }
}

component.ts file:

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

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {

  column: Column;
  Filter: Column[]=[new Column("1","ABC","Column1",""),
  new Column("2","ABC","Column2",""),
  new Column("3","ABC","Column3",""),
  new Column("4","ABC","Column4","")];
  constructor() { 
 // this.Filter=new Column(id="",type="",name="")
  }

  ngOnInit() {
  }
  fFilter(){
    var requiredValue="";
    this.Filter.map(
      x=>requiredValue+=(x.key+"="+x.value+",")
    );
    alert(requiredValue);
  }
}

In essence, I have altered how arguments are passed from the HTML file to the typescript file. However, the data retrieved in the fFilter() function remains consistent and can be utilized based on your specific requirements.

Answer №2

When I examine my code, it appears that the function called in the HTML file simply maps the columns created on the .ts side. However, I believe there may be a missing link between the HTML and .ts files that is meant to pass the desired values (specifically, column.key and input value).

In HTML:

<th *ngFor="let column of entityList.metadata.advancedFilter" >
     <tr>{{ entityName.toLowerCase() + '.' + column.key | translate}}: <input type="{{column.type}}" id="{{ column.key }}" name="{{ column.key }}" autocomplete="off"  [(ngModel)]="column.value" >  </tr>
</th>
<div class="col-sm-9">
     <button class="btn btn-success" type="submit" (click)="advancedFilter()">Search</button>
</div>

In .ts File:

...
import { Column} from '../../models/entity-list.model';
...
export class EntityListComponent implements OnInit {

    column: Column;
    Filter: Column[]=[new Column("code","text","Column1",""),
        new Column("title","text","Column2",""),
        new Column("description","text","Column3",""),
        new Column("entryDate","date","Column4",""),
        new Column("endSubmissionDate","date","Column4","")];

....

    advancedFilter(){
        var requiredValue="where ";
        this.Filter.map(
            x=>requiredValue+=(x.key+"="+"'"+x.value+"'"+" AND ")
        );
        requiredValue = requiredValue.slice(0, -5);
        alert(requiredValue+";");
    }

In entity-list.model.ts:

...
export class Column{
    public key:string;
    public type:string;
    public name:string;
    public value:string;
    constructor(key:string,type:string,name:string,value:string)
    {
        this.key=key;
        this.type=type;
        this.name=name;
        this.value=value;
    }
}

Current Output: https://i.sstatic.net/R8AfQ.png

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

404 error received from Angular 2 API call despite successful testing of service

I've been attempting to make a web service call from my Angular 2 application. private baseUrl: string = 'http://localhost:3000/api'; getPatterns(): Observable<Pattern[]> { const patterns$ = this.http .get(`${this.baseUrl ...

Check out the computed typescript types

In my work with TypeScript types, I find myself frequently using Omit, Pick, and similar tools based on other types. While it generally gets the job done, I often struggle with readability when dealing with complex type manipulations. I am interested in f ...

Unable to resolve external modules in TypeScript when using node.js

I wanted to integrate moment.js into my node application, so I proceeded by installing it using npm: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc0c2c0c8c3d9ed9f8399839d">[email protected]</a> J ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

Angular Universal SSR - prerendering static content

After updating to the latest Angular version 10, I encountered an issue when trying to run a static prerender. The error message displayed is: Unhandled Promise rejection: Cannot read property 'moduleType' of undefined. Despite trying various con ...

Having trouble correctly initializing RequestOptionsArgs for a POST request in the service function

Recently, I have been working with Angular 6 and decided to follow a helpful video tutorial on image submissions (link to the video). My goal is to track the progress of the form submission in order to display the percentage of the uploaded file. In my c ...

Exploring the fusion of different interfaces and props in React using typescript

I have designed an interface as shown below, representing the "base button". export interface ButtonProps { backgroundColor?: Colors, children?: React.ReactNode | JSX.Element, style?: CSSProperties, disabled?: boolean, onClick?: () => ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Unable to enhance Request using Typscript in nodejs

In my middleware, I am attempting to enhance the Request by adding a property called user. However, I encountered this error: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>' I am trying to u ...

Convert the generic primitive type to a string

Hello, I am trying to create a function that can determine the primitive type of an array. However, I am facing an issue and haven't been able to find a solution that fits my problem. Below is the function I have written: export function isGenericType ...

In TypeScript, make sure to verify the type of an object to avoid any potential compilation errors stemming

Here is the code snippet: export default class App { el: HTMLElement; constructor(el: string | HTMLElement) { if (typeof el === "string") { this.el = document.getElementById(el); } if (typeof el === typeof this.el) { t ...

Navigating with Angular 2 using separate modules but sharing the same routing

What if I have two main routes, both loading the same child module? Is it possible to have two routes with the same name on the child module that load two different components based on the main route? Main Routes: export const ROUTES: Routes = [{ pat ...

Issue: Incorrect parameter supplied for pipe 'AsyncPipe' in MatTable Angular 11

Currently, I am working on integrating Angular MatTable with an async pipe. The data is retrieved from a RESTAPI as an Observable. However, when I attempt to utilize ([dataSource] = "dataSource | async") in this manner, it results in the error described ab ...

Exploring Angular: Adding elements to formArray and tracking form value modifications

I am currently working on a Form that utilizes a formArray : initForm() { this.mainForm = this.formBuilder.group({ foos: this.formBuilder.array([], [Validators.required]), }); getFoos(): FormArray { return this.mainForm.get(&apos ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

The custom loader for Webpack (haml-haml-loader) appears to be malfunctioning

I am fairly new to managing my own Angular applications. I found this helpful guide for setting up haml loading through webpack. However, the guide is quite outdated and ngx no longer supports eject, so I am experimenting with this package to customize web ...

Barreling is essential for TypeScript custom paths to function properly

This morning has been dedicated to exploring ts-paths in order to shorten my import paths. After some experimentation, I have found that custom paths do work IF you set up barreling (having an index file that exports your modules) root ├── client ...