使用Angular模板参考将动态值附加到动态文本字段

时间:2019-12-02 06:22:03

标签: javascript angular

我有以下html代码,当我单击按钮时需要更改同一行文本字段的值。我的问题是如何引用输入字段并附加值?

app.component.html

<div *ngFor="let item of [1,2,3,4]; let i = index">
  <input type="text" #textField{{i}} />
  <button #btn{{i}} (click)="myEvent(i)">Click to Change</button>
</div>

app.component.ts

export class AppComponent  {
  myEvent(i) {
    if(i == 0) {
      // textField0 append a new value to the text field
    }
  }
}

谢谢

Sample demo here

3 个答案:

答案 0 :(得分:2)

尝试不使用#template参考变量,而只使用[(ngModel)]

HTML:

<div *ngFor="let item of [1,2,3,4]; let i = index">
    <input type="text" [(ngModel)]="value[i]"/>
    <button #btn{{i}} (click)="myEvent(i,value[i])">Click to Change</button>
</div>

<p *ngFor="let item of data">
    {{item}}
</p>

TS:

value = [];
data = [];

myEvent(i, value) {
  this.data[i] = value;
}

Demo

答案 1 :(得分:2)

使用@ViewChildren()的另一种方法:

HTML:

<div *ngFor="let item of [1,2,3,4]; let i = index">
  <input type="text" #textField />  -- Here just use `#textField` without index
   <button #btn{{i}} (click)="myEvent(i)">
    Click to Change
   </button>
</div>

TS代码:

@ViewChildren("textField") textFields: QueryList<ElementRef>;

myEvent(i: any) {
  var feildsArray = this.textFields.toArray();
  feildsArray[i].nativeElement.value = "James";
}

Working_Demo

答案 2 :(得分:1)

您可以做出类似的事情

interface InputModel {
  id: number;
  value: number;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public inputs: InputModel[] = [
    {id: 1, value: 0},
    {id: 2, value: 0},
    {id: 3, value: 0},
    {id: 4, value: 0},
  ]

  public updateValue(index: number, valueString: string): void {
    this.inputs[index].value = this.inputs[index].value + 1;
  }
}

您的模板将是

<div *ngFor="let item of inputs; let i = index">
  <input type="text" [value]="item.value"/>

  <button (click)="updateValue(i, item.value)">Click to Change</button>
</div>