在ngFor中访问局部变量

时间:2018-07-18 15:21:57

标签: angular

在Angular 5中,如何在这种情况下设置和访问本地#variable?

<div *ngFor="let p of model; index as i">

    <!-- field -->
    <input
        type="text" 
        required
        [(ngModel)]="model[i].ti"
        #ti{{i}}="ngModel"
        #tiRef{{i}}
        id="ti"
        name="ti"
    >

    <!-- counter -->
    <div class="counter">
        {{ (tiRef[i].getAttribute('maxlength')) - tiRef[i].value.length }}
    </div>

    <!-- validation -->
    <div *ngIf="ti[i].touched && !ti[i].valid && ti[i].errors && ti[i].errors.required">
        Please enter a title.
    </div>

</div>

2 个答案:

答案 0 :(得分:1)

您可以给template reference variables赋予简单的名称,并像往常一样引用它们。变量是为ngFor循环的每次迭代定义的,并且可以在该迭代的上下文中使用(有关示例,请参见this stackblitz)。如果在form标签中使用了标记,请确保每个input字段都具有唯一的name

<div *ngFor="let p of model; let i=index">

    <input 
      type="text" 
      required 
      [(ngModel)]="p.ti" 
      #ti="ngModel" 
      #tiRef 
      [name]="'ti' + i">

    <div class="counter">
        {{ tiRef.getAttribute('maxlength') - tiRef.value.length }}
    </div>

    <div *ngIf="ti.touched && !ti.valid && ti.errors && ti.errors.required">
        Please enter a title.
    </div>

</div>

答案 1 :(得分:0)

您需要的是ViewChildren

下面是您尝试使用它的一种方法。

@ViewChildren('tiChildren') tiChildren: QueryList<any>;

tiChildrenArray: any[] = [];

constructor() {
    tiChildrenArray = this.tiChildren.toArray();
}


<div *ngFor="let p of model; index as i">

    <!-- field -->
    <input
        type="text" 
        required
        [(ngModel)]="p.ti"
        #tiChildren
        id="ti"
        name="ti"
    >

    <!-- counter -->
    <div class="counter">
        {{ (tiChildrenArray[i].getAttribute('maxlength')) - tiChildrenArray[i].value.length }}
    </div>
</div>