PrimuS
PrimuS

Reputation: 2683

Get length of text in *ngFor

I am fairly new to Angular (8) and I try to get the length of the input value, which I created in a *ngFor like this:

<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 would I access the length of the panel.title in my class?

This is my interface/class

export interface ProgressbarStepData {
    // Each progressbar step is represented by an instance of this data type.
    id: number; // Unique ID
    title: string; // The label that is displayed as the step title.
    color: string; // Hex code of the colored markings associated with this step. Only visible in Builder, not Viewer.
    order: number; // Denotes which step this is (from step 1 to <number of steps>)
}

export class ProgressbarEditorComponent implements OnInit {
    public panels: Array<ProgressbarStepData> = []; // One panel for each existing progressbar step

   ...

What would I need to get the length of the input currently typing in?

EDIT

To clarify what I want to achieve: I want to count the characters typed in the CURRENT input and trigger an alert from the class (not from the template itself)

Upvotes: 2

Views: 1393

Answers (3)

Manzer A
Manzer A

Reputation: 3826

.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;
}

Upvotes: 0

nash11
nash11

Reputation: 8680

Your ngModel needs to be bound to panels not to panel in the ngFor. You can do this using the index.

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

Then trigger the alert in the component by passing in the index and use that to get the length of the panel title. I have used the blur event here.

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

Upvotes: 2

rafi muhammad
rafi muhammad

Reputation: 192

Try This,

<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="Bezeichnung" [(ngModel)]="panel.title" />
</div>


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

Upvotes: 1

Related Questions