Easy way to position cursor to new line?

I am hoping this is pretty easy since it seems like a common case.

I have an custom element that has some code that when they update the last line in the list adds a new blank line. I would like to position to the first input on that line. I am pretty sure the problem is that the element doesn’t exist when I try to set focus so nothing happens. I could potentially just have a new blank line that is hidden and then unhide/ add new hidden line but was wondering if there is a better way. Here is some code:

public amountChanged(index: number) {
    if (index === this.job.jobDetails.length - 1) {
        this.addJobDetail();
        document.getElementById("co_" + index).focus()
    }
}

addJobDetail() {
    if (!this.job.jobDetails) {
        this.job.jobDetails = new Array<JobDetail>();
    }

    let jobDetail = new JobDetail();
    this.job.jobDetails.push(jobDetail);
    this.attachJobDetailValidation(jobDetail);
}

Thanks for any ideas!

1 Like

You’d need to perform the Focus in the next macroTask using either TaskQueue.queuyTask or a setTimeout. The problem is exactly as described, the DOM element isnt yet rendered when you’re trying to do it sync as you are

3 Likes

Thank youy @zewa666, worked great and was very simple to implement.

1 Like

Good to hear. Just for completeness, the taskqueue approach should be favoured as it allows easier unit testing vs having to manipulate clock timings for setTimeout.

2 Likes

I also find that unit testing against the taskqueue is far more straightforward than setTimeout, thanks to flushTaskQueue and flushMicrotaskQueue

2 Likes

@zewa666 Is TaskQueue presented anywhere in the documentation (aside from it’s definition in the API section)? I feel like I’ve been around the block and have never heard about this feature. Aside from this four year old blog post, is there anything in the official docs that teaches someone how to use this?

1 Like

I dont think so tbh. Its a not so common use case thats why it might fell under the radar. The linked article from @dwaynecharrington explains it very well and a minimal sample showing how its used in unittests with flushing should cover everything there is. Perhaps we can reuse that content or parts of it for the official docs

2 Likes