猿问

获取 *ngFor 中的文本长度

我对 Angular (8) 还很陌生,我尝试获取输入值的长度,我以*ngFor如下方式创建了它:


<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>

我将如何访问panel.title班级中的长度?


这是我的接口/类


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


   ...

我需要什么才能获得当前输入的输入长度?


编辑


澄清我想要实现的目标:我想计算在 CURRENT 输入中键入的字符数并触发来自类的警报(而不是来自模板本身)


Qyouu
浏览 165回答 3
3回答

忽然笑

.html<input type="text" (input)="inputMthd($event)"&nbsp; (keyup)="methodCalled($event)">.tsinputMthd(e){console.log(e);event.target.value.length;}methodCalled(e){console.log(e);e.target.value.length;}

开满天机

您ngModel需要绑定到panels不panel中ngFor。您可以使用index.<div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id">&nbsp; &nbsp; <div>{{ panel.title }}</div>&nbsp; &nbsp; <input matInput placeholder="Bezeichnung" [(ngModel)]="panels[i].title" (blur)="showAlert(i)" /></div>然后通过传入索引并使用它来获取面板标题的长度来触发组件中的警报。我在blur这里使用了这个事件。showAlert(index) {&nbsp; &nbsp; const titleLength = this.panels[index].title.length;&nbsp; &nbsp; // Call alert with the length of the title here.}

达令说

尝试这个,<div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id">&nbsp; &nbsp; <div>{{ panel.title }}</div>&nbsp; &nbsp; <input (change)="onChange({{panel.title}})" matInput placeholder="Bezeichnung" [(ngModel)]="panel.title" /></div>onChange(title) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(title.length);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答