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.

4
  • it works for last child too stackblitz.com/edit/ngstyle-examples-acbg6k. can you provide problem in this stackblitz? Commented Mar 10, 2019 at 10:38
  • @FatemeFazli add another input type like a button and it won't work Commented Mar 10, 2019 at 12:41
  • now check the stackblitz again. Commented Mar 10, 2019 at 12:49
  • yes, I agree but my angular html structure will be this one: pastebin.com/fycs1pgj Commented Mar 10, 2019 at 12:59

2 Answers 2

2

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

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.