Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below:

<div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id">
    <div>{{ panel.title }}</div>
    <input matInput placeholder="Bezeichnung" [(ngModel)]="panel.title" />
</div>

How can I access the character length of the panel.title from my component?

This is my interface/class structure:

export interface ProgressbarStepData {
    id: number;
    title: string;
    color: string;
    order: number;
}

export class ProgressbarEditorComponent implements OnInit {
    public panels: Array<ProgressbarStepData> = [];

   ...

What do I need to do in order to get the character length of the input currently being typed in?

EDIT

To clarify, I want to be able to count the characters being typed in the current input field and trigger an alert from within the component, not directly from the template.

Answer №1

Make sure your ngModel is bound to the array panels, not just a single element panel in your ngFor loop. Remember to use the index of the iteration to correctly bind the values.

<div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id">
    <div>{{ panel.title }}</div>
    <input matInput placeholder="Label" [(ngModel)]="panels[i].title" (blur)="showAlert(i)" />
</div>

You can then trigger an alert from the component by passing in the index and accessing the title length of that specific panel. Utilize events like blur for this purpose.

showAlert(index) {
    const titleLength = this.panels[index].title.length;
    // Invoke alert with the title length information.
}

Answer №2

Give this a shot,

<div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id">
    <div>{{ panel.title }}</div>
    <input (change)="onChange({{panel.title}})" matInput placeholder="Description" [(ngModel)]="panel.title" />
</div>


onChange(title) {
          console.log(title.length);
         })

Answer №3

.html

<input type="text" (input)="inputMthd($event)"  (keyup)="methodCalled($event)">

.ts

inputMthd(e){
console.log(e);
event.target.value.length;
}
methodCalled(e){
console.log(e);
e.target.value.length;
}

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

Access the session on both routers

I currently have 2 different routers set up in my application: Router 1 app.post('/consultations', function(req, res) { req.session.name = 'administrator'; console.log('test', req.session.name); // the session is pro ...

Struggling to connect to Node/Express Backend

I have developed a backend service using Node and Express. However, I am encountering an issue where none of the routes for this application are being accessed. Despite expecting to see an error message in the console if the routes were misconfigured, no s ...

Passing specific props to child components based on their type in a React application using TypeScript

Sorry if this question has already been addressed somewhere else, but I couldn't seem to find a solution. I'm looking for a way to pass props conditionally to children components based on their type (i.e. component type). For example, consider ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Tips for integrating both client-side and server-side validation techniques in your web application

After conducting some research, I have come across information indicating that it is feasible to implement both client-side and server-side validation simultaneously. However, my focus is not solely on learning JavaScript; I am also interested in utilizi ...

Is it possible to compare escaped data with the unescaped value of a select box in JavaScript?

On my webpage, I have a functionality that involves fetching select box options through an AJAX request. I then create the select box based on this data, and later use the selected option to retrieve additional information from the response received via AJ ...

Mapping type property names in Typescript for substitution

I am working on a function that accepts two objects as parameters: one representing a model and the other representing a mapping. The function then returns an object with two properties: one showing the base model and the other displaying the model with ea ...

What steps do I need to take to generate a terrain similar to this using Three.js?

Trying to construct a terrain based on a heightmap with an enclosed bottom layer. Refer to this example for clarification: The current function for generating the terrain is as follows: var img = document.getElementById("landscape-image"); var numSegment ...

Intercepting HTTP responses to handle headers

I'm facing an issue where I am trying to retrieve a custom header sent from the server in my $http response interceptor. However, the only header that is accessible is the Content-type header. How can I troubleshoot this problem? Here is part of my $ ...

Sending data through a form using AJAX and PHP

Greetings! I've developed a page that allows users to view results for a specific tournament and round. The user will first select a sport, which will then populate the available tournaments based on the sport selection. Following this, the user can ...

Utilizing the dollar shorthand for jQuery in conjunction with Selenium

While utilizing the Selenium addon along with jQuery in my project, I encountered an issue where the use of jQuery functions containing $ in Selenium would trigger a "function not found" error. The problem was resolved by removing jQuery, but using jQuer ...

Troubleshooting: React js Project console.logs are not being displayed in the browser's

When working on my current project, I noticed that any time I try to use console.log in the dev tools, it shows as cleared. Strangely, console.log works fine in my other projects. Does anyone have an idea how to resolve this issue? Here is a screenshot of ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

Navigating the path for the script src dynamically with the help of Angular.js and Javascript

I could really use some assistance. I am trying to dynamically set the js/css path name using Angular.js/Javascript/Jquery. Let me explain my code below. <script src="/crm/controller/productController.js" type="text/javascript"></script> Let& ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

Upload the image data into the input file tag

Is there a way to take a string code stored in a JavaScript variable that is retrieved from the Cropit plugin (used for cropping images) and then set this information into an input file tag? I want to be able to send it via AJAX to PHP. Here is the JavaSc ...

Instructions for utilizing a non-string reference without triggering flow errors

I've noticed that string refs are considered legacy in React. You can read more about it here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md However, I am encountering a flow error in my component and I&apo ...