简体   繁体   中英

Template reference variables *ngFor

item.component.html

 <div class = "col text-center" *ngFor="let item of items">
 <p> item :{{item}} </p>
 <ion-input type="text" #input (ionFocus)="myFocusVar #input>

 </div>
 <ion-button type="submit" (click)="editInput()"></button>

item.component.ts

@Component({
selector: 'item',
templateUrl: './item.component.html'
})
export class DetailComponent {
@ViewChild('input') myInput ;

items =["item1","item2","item3"]

editInput(){
let key = "|"
let v = this.myInput

if (this.myFocusVar== true){v.value += key} }

}
else {console.log('false')}

I want to edit my Input with a button when it Has the focus on, for example, if I enter a word and click on the button, it should add "|" after the word I entered. I prefer to not put the button inside of the div, I want a single button for all.

The problem : If I focus the second input and I click the button, it will add "|" to the first input and not to the second, the same for the third input.

Do you have any idea how to fix this problem? or maybe a simple example to help me understand ?

Since your code generates multiple ion-input elements, you should probably use 'ViewChildren' and 'QueryList' rather than the singular 'ViewChild'.

 import { Component, ViewChildren, QueryList } from '@angular/core'

I'm not sure if 'ion-input' is its own component. If it is, you can import it as well and query for it.

 import { IonInputComponent } from './wherever'  

then to query:

 @ViewChildren(IonInputComponent) inputs: QueryList<IonInputComponent>;

You would not need individual template reference variables if you queried them like this. Then you should be able to access that list in ngAfterViewInit or later. If you need the list as an array, you can call

 this.inputs.toArray(); 

You should be able to read each of the component's properties. Although its unclear from your code what you are doing with (ionFocus) bc I think you may have a typo / missing quotation mark there.

EDIT - I'm not sure what you're (ionFocus) line is supposed to do, but if you're trying to set a variable specifying which of the inputs has been focused. You can just use index numbers.

  *ngFor="let item of items; let i = index"

And then

 (ionFocus)="myFocusVar = i"

That way , when you focus one of the inputs, myFocusVar will change to its index. Then you can use that index to reference the correct input from your QueryList.

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