1

How can I get the last child of input type text inside an nGfor ? For first child:

span:first-child > input[type=text] 
it works just fine but for last-child the dom doesn't seem to have a last-child..Angular 6 here.
Mikael Ken
  • 41
  • 1
  • 10

2 Answers2

1

You can use ViewChildren (in stackblitz if you open the page in new window, at first the last element get the focus, each time you push "add button" the last element get the focus too.

The idea is has a series of inputs with reference name, e.g. input

<p *ngFor="let i of elements"><input #input ></p>

You define

  @ViewChildren('input') inputs:QueryList<ElementRef>

In ngAfterViewInit

  ngAfterViewInit() {
    this.inputs.last.nativeElement.focus()

    this.inputs.changes.subscribe(() => {
        this.inputs.last.nativeElement.focus()
    })
  }

We must subscribe to this.inputs.changes if our code allow change the number of inputs.

NOTE:In the stackblitz I use a tipical pipe(takeWhile(()=>this.alive) to unsubscribe on Destroy the component

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

I think you just want to change the class of the last item, so I used Eliseo code but instead of listening to changes I just check if that element is last item in elements in creation time. maybe you do not need that listening complexity.

https://stackblitz.com/edit/angular-l5ccns

<button (click)="elements.push(1)">add</button>
<p *ngFor="let i of elements; let ind = index"><input #input [ngClass]="{'lastItem': ind === elements.length-1}" ></p>
Mazdak
  • 650
  • 5
  • 13