Rijo
Rijo

Reputation: 3043

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

Upvotes: 1

Views: 2614

Answers (3)

Adrita Sharma
Adrita Sharma

Reputation: 22213

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

Upvotes: 2

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

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

Upvotes: 2

Evgeniy Boytsov
Evgeniy Boytsov

Reputation: 314

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>

Upvotes: 1

Related Questions