1

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

1
  • can you specify the possible result that you want to achieve or some sample output. didn't understand the end result or what you are trying to achieve? Are you trying to get the value into the text field ? Commented Dec 2, 2019 at 6:27

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

No, but he can use it foe some other purpose like validation or something
1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.