简体   繁体   中英

Dynamic value append to the dynamic text field using Angular template reference

I have following html code, when I click on the button need to be change same row text field value. My question is how to refer the input field and append the value?

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

Thanks all

Sample demo here

Try without using #template reference variable and just use [(ngModel)] instead:

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

Another way by using @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 Code:

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

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

Working_Demo

You can make something like this

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

And your template will be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM