Tips for keeping your attention on the latest HTML element

Welcome to my HTML Template.

<div
        cdkDropList
        class="document-columns__list list"
        (cdkDropListDropped)="dragDrop($event)"
    >
        <div
            cdkDrag
            class="list__box"
            *ngFor="let column of columns; let i = index"
            (click)="selectColumn(column)"
            [class.list__box_selected]="column === selectedColumn"
        >
            <div class="list__placeholder" *cdkDragPlaceholder></div>
            <div class="list__content">
                <div class="list__name">
                    {{column.col_num}}. {{column.title}}
                </div>
                <div class="list__type">
                    {{getType(column)?.title}}
                </div>
            </div>
            <p-button
                class="list__button"
                icon="pi pi-trash"
                styleClass="p-button-danger p-button-outlined"
                [disabled]="columns.length === 1"
                (click)="deleteColumn(column)"
            ></p-button>
        </div>
    </div>
    <div class="document-columns__button">
        <p-button
            styleClass="p-button-secondary p-button-outlined"
            (click)="addNewColumn()"
            label="Add column"
            icon="pi pi-plus"
            iconPos="left"
        >
        </p-button>
    </div>

Here is my TS code snippet.

 public addNewColumn(): void {
    const arrayLength: number = this.columns.length + 1;
    this.columns.push({
        col_num: arrayLength,
        type_id: TypeId.Number,
        title: 'New Column',
    });
    this.columnsChanged.emit(this.columns);
    this.recalculateColumnNumbers();
}

Whenever I click the "add column" button, a new element gets added to the array and the template refreshes with the addition. My goal is to focus on the newly added element afterward. How can I achieve this? I've attempted to use the following code, but it hasn't been successful.

document.querySelectorAll('.document-columns__list:last-child').focus();

Answer №1

If you want to focus on the last element you added in your addNewColumn method, you can achieve this by waiting for the element to be rendered in the dom. In the example below, I delayed the focus action using setTimeout. It's best practice to use Angular's way to query an html element. You can make use of the ViewChildren decorator.

@ViewChildren('element', { read: ElementRef }) elements: QueryList<ElementRef>;

 public addNewColumn(): void {
....
  setTimeout(() => 
    this.elements.last.nativeElement.focus()
    );
}

To allow the component class to access the element you want to focus on, simply add a template variable #element in your template.

<div #element></div>

You can see a working example here: https://stackblitz.com/edit/angular-ivy-nszzdt

Answer №2

@ViewChildren('element', { read: ElementRef }) public elements!: QueryList<ElementRef>;

public createNewColumn(): void {
    const totalColumns: number = this.columns.length + 1;
    this.columns.push({
        col_num: totalColumns,
        type_id: TypeId.Number,
        title: 'Add column',
    });
    this.columnsChanged.emit(this.columns);
    this.updateColumnNumbers();
    setTimeout(() => this.elements.last.nativeElement.click());
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Global registration of router directives with Angular router RC3 is required

I'm trying to avoid registering the Router_Directives for each individual component. Instead, I would like to apply it globally similar to how I did before: import { RouterConfig ,Router, ActivatedRoute, ROUTE_PROVIDERS} from '@angular/router&a ...

Error encountered during test execution with Angular 2 template parsing issue

I have a basic component that I am working with: galery.component.ts import {Component, Input} from '@angular/core'; @Component({ selector: 'galery-component', templateUrl: 'galery.component.html', styleUrls: ['g ...

Guide to creating the shared section of two wheels with CanvasRenderingContext2D

Is it possible to dynamically draw the shared area of two circular shapes using JavaScript and CanvasRenderingContext2D? My ultimate goal is to be able to adjust the size of the shape, ranging from a complete circle to a mere point. The desired outcome is ...

AngularJS UI-Router in hybrid mode fails to recognize routes upon initial page load or reload

It appears that when using the @ui-router/angular-hybrid, routes registered within an ng2+ module are not being recognized during the initial load or reload. However, these same routes work fine when accessed by directly typing the URL. I have followed th ...

The console errors in the test are being triggered by the Angular setTimeout() call within the component, despite the test still passing successfully

I am currently experimenting with a click action in Angular 7 using an anchor tag Below is the markup for the anchor tag in my component <div id="region-start" class="timeline-region"> <div class="row"> <div class="col-12 col-md- ...

Exploring the population with embedded RxJs queries

I'm struggling to find a solution to this particular issue. Imagine there is an object type described as follows: Box { Fruit[n]: { Kinds[n]: { id: string; name: string; } } } From an API call, I received a bo ...

react-mock-store: Error - the middleware function is not defined

In my current setup, I am utilizing jest for testing with React and Typescript. import configureStore from "redux-mock-store"; import thunk from "redux-thunk"; const mockStore = configureStore([thunk]); it("should handle fetchCha ...

Utilize the function specified in an external file

In my project, I have a typescript file named "menuTree.ts" which compiles to the following JavaScript code: define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Menu ...

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

Adjust the setting for the useHash parameter within the RouterModule during execution

I am faced with a situation where I need to dynamically load my router module option useHash in my Angular application, sometimes with true and other times with false. This decision depends on the server state data that is available in the global window ob ...

Troubleshooting Node.js import module errors

I have just discovered two files that I created using the TS language specification manual (on page 111). The first file, called geometry.ts, contains the following code: export interface Point { x: number; y: number }; export function point(x: number, y ...

Angular template is failing to reflect changes in my variable

My chrome extension has a background script that updates an array named history. I want to display the number of "type 1" entries in real time on my popup. Here is how I am managing it in my .ts file: history: Report[] = []; classOne = 0; classOne ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Enhance Chatbot-ui by integrating GPT-4V (Vision) functionality, enriching the open-source ChatGPT clone developed in TypeScript

Is there a way to integrate GPT-4 Vision API into Chatbot-ui, the fantastic open-source alternative to ChatGPT created by McKay Wrigley? This tool allows you to access OpenAI AI models using your own API key, which is truly remarkable. I have been using i ...

Whenever I update the values in my input using the ngModel attribute, all of my arrays stored in an object also get updated

I am currently working with a table on the frontend. <table class="table table-hover"> <thead> <tr> <th> Account Entry Number </th> <th> ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Exploring the Component API in VueJS 3 with Typescript: Learn how to assign a class to a template ref

Is there a recommended way to add/remove CSS classes from a template ref using the Vue 3 Composition API and typescript? When trying to use modal.value, I encountered the following typescript errors: const modal = ref(null) results in Object is possibly ...

Deriving a universal parameter from a function provided as an argument

My function can take in different adapters along with their optional options. // Query adapter type 1 type O1 = { opt: 1 } const adapter1 = (key: string, options?: O1) => 1 // Query adapter type 2 type O2 = { opt: 2 } const adapter2 = (key: string, opti ...

Achieving text alignment with icons in Angular

I'm having trouble aligning my text with the icon next to it despite trying to adjust margins. I would really appreciate any help or suggestions on how to resolve this issue. <div class="notification" [ngClass]="{'no ...