Angular for Multi-Input Fields

I'm currently working on a task in Angular 9 where I need to create an input field that behaves differently for each letter. However, the main issue I'm facing right now is related to change detection. There seems to be a conflict between two possible solutions. Using changes.subscribe() with @ViewChildren() doesn't respond well when I implement a custom trackBy within my *ngFor loop. Yet, the trackBy is crucial to prevent issues with changes in one box affecting another. While I could use the custom trackBy function, it lacks access to data from my Component. Below is the code snippet of my component:

@Component({
  selector: 'app-multiple-fields',
  templateUrl: './multiple-fields.component.html',
  styleUrls: ['./multiple-fields.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => MultipleFieldsComponent),
    },
  ],
})
export class MultipleFieldsComponent
  implements OnInit, AfterViewInit, ControlValueAccessor {
  @Input() numFields: number = 6;
  @ViewChildren('input', { read: ElementRef }) inputs: QueryList<
  ElementRef
  >;
  fields: string[];

  onChange: any = () => {};
  onTouch: any = () => {};

  ngAfterViewInit() {
    this.inputs.changes.subscribe((next: QueryList<ElementRef>) => {
      let val = next.map((el) => el.nativeElement.value).join('');
      this.onChange(val);
      this.onTouch(val);
    });
  }

  ngOnInit() {
    this.fields = Array(this.numFields).fill('');
  }

  trackArray(index, item) {
    return index;
  }

  writeValue(value: string) {
    if (value.length == this.numFields) this.fields = value.split('');
  }

  registerOnChange(fn: any) {
    this.onChange = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouch = fn;
  }
}

Below is the template code for the component:

<input
  #input
  *ngFor="let item of fields; let i = index; trackBy: trackArray"
  [(ngModel)]="fields[i]"
/>

I'm aiming to monitor any changes in the fields[] array and trigger onChange() and onTouch() functions with the combined value for using [(ngModel)] in the component instance. Any assistance on resolving this issue would be highly appreciated. Thank you!

Answer №1

Perhaps I may not be fully comprehending your intention, but have you considered utilizing Angular's change event?

<input *ngFor="let item of fields" (change)="itemChanged(item)">

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

What is the best way to implement a condition within an ngFor loop in Angular?

I am looking to iterate the user list with a condition. <li *ngFor="let user of users" *ngIf="user.age>25"> {{user.name}} </li> I understand that this code is incorrect. However, I would like to achieve something similar. Is there any way ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

The process of invoking the AsyncThunk method within the Reducer method within the same Slice

Within my slice using reduxjs/toolkit, the state contains a ServiceRequest object as well as a ServiceRequest array. My objective is to dispatch a call to a reducer upon loading a component. This reducer will check if the ServiceRequest already exists in ...

Enhance Data Grid functionality in Angular 8 using DevExpress library

I'm struggling to grasp how the DxDataGridComponent extension works. My first step is extending the DxDataGridComponent like this: import { Component } from '@angular/core'; import { DxDataGridComponent } from 'devextreme-angular/ui/d ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

When making a GET request with Angular and NodeJS that includes parameters, only the response object is returned without any associated

Let's say I have a URL like 'localhost:3000/verify/a5d5sd', which I send to a user via email. When the user clicks on this link, I use the parameter (a5d5sd) in the link to check some conditions on the server and in my MongoDB database. The ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...

Unable to exclude modules from ng-build in Angular CLI, the feature is not functioning as intended

I am managing an Angular CLI project that consists of two identical apps. However, one app requires the exclusion of a specific module in its build process. Key Details: Angular CLI Version: 1.7.4 Angular Version: 5.2.10 In the angular-cli.json ...

Error 404.0 encountered when refreshing Server Page with Angular Routing

I have integrated Angular 7 into my project and configured the routing as follows: app.routing-module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { Test1Component } from ...

What is the best way to use a single schema in MongoDB to create an object with an array?

Currently, I am working on creating a single Schema for Author with their respective quote. Here's what my model looks like at the moment: const mongoose = require("mongoose"); const AuthorSchema = new mongoose.Schema({ name: String, quote: ...

Adding a new value to a string variable using TypeScript

Just starting out with Angular and I'm looking to capture user input from a text box with each keystroke and add it to a string variable like in Java. In my text box, I have the following setup for capturing key events: <input type="text" ...

Maintaining the original function signature upon returning it

I am attempting to develop an interceptor function, specifically a throttle function. Let's look at this example: function throttle(func: Function, wait: number = 0): Function { let previous: { args: any[]; timestamp: number; ...

Retrieve information for the designated page exclusively

When retrieving data from the backend using a service, I encounter an issue where the system may slow down if 2000 records are returned in one request. To address this, I would like to display only 10 records per page and fetch the next 10 records with eac ...

Dynamically import Angular 2 components from external resource files in code

Exploring the capabilities of Angular2 rc.4 - rc.5 Is it feasible to dynamically import components? Consider the scenario where I have these import statements: import {HelloComponent} from './hello.component'; import {IncComponent} from ' ...

Unsubscribing EventListener during ngOnDestroy

Here is my implementation of a directive in Angular. I am facing an issue with removing the event listener in this case: import { Directive, ElementRef, OnDestroy } from "@angular/core"; @Directive({ selector: "[Enter]" }) export class Enter implemen ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

Ensuring either of two properties is required in a Typescript Class

DISCLAIMER: While this question may seem similar to a thread on Stack Overflow, the solutions provided there do not apply to Classes. Due to the limitations in extending interfaces with classes, I'm facing a challenge. I have encountered an intriguin ...

Create a function that takes two arrays as input and assigns variables to store the matching and non-matching elements between the two arrays

Definition of Interface - interface I { name: string; age: number; size?: string; } Arrays Initialization - let firstArrayMatches: I[] = []; let firstArrayUnmatches: I[] = []; let secondArrayMatches: I[] = []; let secondArrayUnmatches: I[] = []; I ...