typescript 如何在 *ngFor 中设置唯一的模板引用变量?(角)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48347854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:11:03  来源:igfitidea点击:

How to set unique template reference variables inside an *ngFor? (Angular)

angulartypescript

提问by florentine

I have a bunch of input fields in a *ngForloop. The documentation says that template reference variables should be unique. Is there a way to do something like #attendee-{{person.id}}to make it unique?

我在一个*ngFor循环中有一堆输入字段。文档说模板引用变量应该是唯一的。有没有办法做一些#attendee-{{person.id}}让它独一无二的事情?

   <div *ngFor="let person of attendeesList">
       <input #attendee [ngModel]="person.name" (blur)="changeName(attendee.value)"/>
   </div>

(I know that there is the option of doing (ngModelChange)="changeName($event)"but there are reasons I need to use blurinstead. Specifically, I don'twant the model to change until the person is done typing the name and we have validated that the name is not empty and not a duplicate name.

(我知道有这样做的选择,(ngModelChange)="changeName($event)"但有一些原因我需要使用模糊代替。具体来说,我希望模型更改,直到该人完成输入名称并且我们已验证名称不为空而不是重复的名字。

回答by yurzui

Your template reference variable is already unique because you use it inside embedded view scope:

您的模板引用变量已经是唯一的,因为您在嵌入式视图范围内使用它:

<div *ngFor="let person of attendeesList">
  <input #attendee [ngModel]="person.name" (blur)="person.name = attendee.value"/>
</div>

Working Example

工作示例

But you can even omit template reference variable as shown below:

但您甚至可以省略模板引用变量,如下所示:

<div *ngFor="let person of attendeesList">
  <input [ngModel]="person.name" (blur)="person.name = $event.target.value"/>
</div>

回答by Explosion Pills

Template variables need to be unique with respect to the template rather than the rendering of the template (the actual values). You want to use ViewChildren.

模板变量需要相对于模板是唯一的,而不是模板的呈现(实际值)。您想使用ViewChildren

@ViewChildren('attendee') attendeeInputs: QueryList<ElementRef>;

You can treat attendeeInputsas a QueryListand operate on each attendee input individually as needed based on iteration of the indices.

您可以将其attendeeInputs视为QueryList并根据索引的迭代根据需要单独对每个参与者输入进行操作。

回答by joshrathke

If you have an iterable series of Inputs in your form and a decent amount of logic regarding how you want the form to respond to user input the ReactiveFormsModuleis going to be a much better fit. This way you don't have to worry about template reference variables and can interact with the FormControls directly.

如果您的表单中有一系列可迭代的 Inputs 并且有相当数量的关于您希望表单如何响应用户输入的逻辑,那么ReactiveFormsModule这将是一个更好的选择。这样您就不必担心模板引用变量,并且可以直接与 FormControl 交互。

Essentially with Reactive Forms it would look something like

基本上使用反应式表单,它看起来像

Component

零件

// Initialize your Form
initForm(): void {
    this.Form = this._FormBuilder.group({
        arrayOfInputs: this._FormBuilder.array(initArray())
    })
}

// Initialize the Array of Inputs 
initArray(): FormGroup[] {
    return [
        { this._FormBuilder.group({ inputValue: [''] }),
        { this._FormBuilder.group({ inputValue: [''] }),
        { this._FormBuilder.group({ inputValue: [''] })
    ]
}

Template

模板

<ng-container formArrayName="formArray">
    <div [formGroupName]="i" *ngFor="let Inputs of Form.get('arrayOfInputs').controls; let i=index">
        <input formControlName="inputValue" type="text">
    </div>
</ng-container>

There's a few things missing here, but generally this is how I build forms that have interable inputs. The major difference is that usually when initializing the FormArray, I am using data pulled from somewhere. It really helps to build your forms in logical chunks.

这里缺少一些东西,但通常这就是我构建具有可交互输入的表单的方式。主要区别在于,通常在初始化 FormArray 时,我使用的是从某处提取的数据。在逻辑块中构建表单确实很有帮助。

Reactive Forms

反应式