Customizing the placeholder text for each mat input within a formArray

I have a specific scenario in my mat-table where I need to display three rows with different placeholder text in each row's column. For example, test1, test2, and test3. What would be the most efficient way to achieve this?

Code Example:

<div formArrayName="rows" *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns">
                  <span id="edit-cell" [formGroupName]="i">
                      <mat-form-field id="edit-calc-input">
                        <label>
                          <input matInput type="text" [formControlName]="column.attribute">
                        </label>
                      </mat-form-field>
                  </span>
                </div>
  // Define input fields for template use
  public attributesWithFormControls = [
    "productNumber",
    "name",
    "weight",
    "amount"
  ];
ngOnInit() {
    this.columns = this.displayedColumns.map(c => c.attribute);

    if (this.dataSource === null) {
      this.dataSource = new MatTableDataSource([]);
    }

    // Initialize myForm
    this.myForm = this.formBuilder.group({
      rows: this.formBuilder.array([this.initItemRows()])
    });
  }

// Getter for easy access to form fields
  get f() {
    return this.myForm.controls;
  }

  get formArr() {
    return this.myForm.get("rows") as FormArray;
  }

  initItemRows() {
    return this.formBuilder.group({
      productNumber: [""],
      name: [""],
      weight: [""],
      amount: [""]
    });
  }

You can view my progress on StackBlitz

Answer №1

IMPLEMENTING FORM CONTROL REVISION

If you wish to implement this using the formGroup, you can achieve it as follows.

Start by creating a helper function that returns placeholder text based on the index.

// Retrieve row placeholder
 getPlaceholder(i) {
   switch (i) {
     case 0:
       return "test";
       break;
     default:
       return "test" + i;
       break;
   }
 }

In your addRow function, obtain the placeholder text and assign it to the property placeholder in your newItem.value object

 addRow() {
   for (let i = 0; i < 3; i++) {
     const newItem = this.initItemRows();
     newItem.value["placeholder"] = this.getPlaceholder(i);
     this.formArr.push(newItem);
     this.dataSource.data = this.dataSource.data.concat(newItem.value);
   }
 }

In your HTML markup, access that property value from the row

<input
    matInput
    type="text"
    [placeholder]="row.placeholder"
    [formControlName]="column.attribute"
 />

STACKBLITZ LINK

https://stackblitz.com/edit/angular-l9x7ac-oxq4qq?file=app/table-basic-example.html


NON FORM CONTROL REVISION

Create a helper function to generate placeholder text based on the index

 // Retrieve row placeholder
  getPlaceholder(i) {
    switch (i) {
      case 0:
        return "test";
        break;
      default:
        return "test" + i;
        break;
    }
  }

In the HTML markup, use the placeholder attribute and invoke the helper function passing i as an argument.

<input
    matInput
    type="text"
    [placeholder]="getPlaceholder(i)"
    [formControlName]="column.attribute"
/>

STACKBLITZ LINK

https://stackblitz.com/edit/angular-l9x7ac-6aq6u6?file=app%2Ftable-basic-example.html


ORIGINAL SUGGESTION

Update your interface to incorporate a placeholder property.

// Interface
export interface MyInterface {
  attribute: string;
  name: string;
  placeholder: string;
}

Add a property with a placeholder value to your column attributes array.

public displayedColumns: MyInterface[] = [
    { attribute: "productNumber", name: "ProductID", placeholder: "test1" },
    { attribute: "name", name: "Name", placeholder: "test2" },
    { attribute: "weight", name: "Weight", placeholder: "test3" },
    { attribute: "amount", name: "Price", placeholder: "test4" }
  ];

In your HTML markup, utilize the placeholder attribute on the matInput and pass your value via

[placeholder]="column.placeholder"

<input
    matInput
    type="text"
    [placeholder]="column.placeholder"
    [formControlName]="column.attribute"
 />

STACKBLITZ LINK

https://stackblitz.com/edit/angular-l9x7ac-psmqzu?file=app/table-basic-example.html

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

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

I'm experiencing unexpected behavior with the use of Mat-Spinner combined with async in Angular 12, particularly when using the rxjs function

I am relatively new to rxjs and it's possible that I'm using the wrong function altogether. Currently, I'm working on a .NET Core 3.1 backend and implementing a two-second delay for testing purposes. I have a service call that I need to mock ...

The service does not fall within the 'rootDir' directory in the Angular secondary module

Encountering an error while compiling an Angular library related to the rootDir of sub libraries library/services/src/public-api.ts:31:15 - error TS6059: File 'C:/libname/library/services/src/orders/orders.service.ts' is not under 'rootDir& ...

Unable to initialize a public variable due to issues with Ionic Storage retrieval

I am currently facing an issue where I am trying to assign a token stored in the Ionic storage module to a public variable. However, when I attempt to set the token and then access it from another function, I encounter an undefined error. Here is the code ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below: export interface IBookR ...

Transmit a form containing a downloaded file through an HTTP request

I am facing an issue with sending an email form and an input file to my server. Despite no errors in the console, I can't seem to upload the file correctly as an attachment in the email. post(f: NgForm) { const email = f.value; const headers = ...

Top-notch approach for consolidating Typescript Declaration files into a single comprehensive file

Is there any efficient way to package declaration files together without using the module declaration approach? declare module "path/to/file" { ... } declare module "path/to/file/sub/file" { ... } and so on. I have encountere ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Difficulty setting up AngularFire in Ionic application

Seeking assistance for the installation of AngularFire in a Ionic 6 project. Encountering an error message: Packages installation failed, see above. Below is the setup details: >> ionic info Ionic: Ionic CLI : 7.0.1 (C:&bsol ...

Guide to Validating Fields in Angular's Reactive Forms After Using patchValue

I am working on a form that consists of sub-forms using ControlValueAccessor profile-form.component.ts form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Valid ...

Vercel is encountering difficulty locating a module or type declaration during the construction of a Next.js application

Currently, I'm facing an issue while trying to deploy a Next.js app to Vercel. The package react-swipeable appears to have its own type declarations but the build fails with the following error: Running "npm run build" ... > next build ... Failed t ...

Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information: fetchLastSyncDate ...

There was an issue encountered while trying to use HTTPS with a self-signed certificate from a

I made the switch to using https for my nodejs server by following these steps: const https = require('https'); const privateKey = fs.readFileSync('sslcert/server.key', 'utf8'); const certificate = fs.readFileSync('sslc ...

What is the reason behind the input text field not preserving its value when disabled?

Currently, I am working on a basic input field that utilizes Angular within StorybookJS. However, I have encountered an issue where the input text field does not maintain its value when the disabled attribute is set to true. For example, if I manually typ ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

Errors in the Latest Release of Angular2 and Visual Studio 2015

After taking a stroll through the Angular 2 Tour of Heroes sample application with the latest Angular 2 version, I decided to host it within a Visual Studio 2015 Empty Web application. Following the Angular sample closely means that I'm not incorporat ...

The module '@angular/compiler-cli/ngcc' is missing and cannot be located while trying to run ng serve

Out of the blue, I started encountering this error. It seems to be related to a version issue with angular-cli, but I'm unable to pinpoint the exact problem. Any assistance would be greatly appreciated! npm i displays some warnings and one compiler e ...