1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Focus on specified element after rerendering

Discussão em 'Angular' iniciado por Green Grasso Holm, Setembro 16, 2024.

  1. In an Angular app, I've got a view that contains a tabbed interface (NgbNav, from Angular Bootstrap). I'm supposing that this component tracks the choice of tab and uses *ngIf or *ngSwitch or a template conditional to display only the selected tab's content.

    The content of each tab begin with an H2 heading of the form

    <h2 tabindex="-1">This Tab's Heading</h2>


    In the component's SCSS file I have

    h2 { border: thick solid orange; }


    The component TypeScript includes

    activeTab = 1;
    previousTab = 0;


    Selecting a tab sets activeTab to the value that corresponds to the tab.

    What I want (for accessibility purposes), when a tab is selected, is for the focus to be set to the H2:

    if (this.activeTab !== this.previousTab) {
    this.previousTab = this.activeTab;
    Nav.jumpTo('h2'); // where static method Nav.jumpTo(selector: string) uses
    // document.querySelector to find the HTMLElement
    // and then calls its focus() method and logs the heading's text
    }


    When I do this in ngAfterViewChecked, I get an error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'attr.tabindex': '-1'. Current value: 'undefined'." I don't even understand this. The string "tabindex" appears nowhere in the TypeScript in my application, so I'm not changing it here. This is being caused by the Nav.jumpTo call.

    When I do it in ngAfterViewInit, nothing happens, nothing is logged.

    When I do it in ngContentAfterChecked, the result varies. Sometimes I see a border pop briefly around the heading on the new tab and then disappear. Sometimes what's logged is the text of the H2 from the previous tab instead of from the newly selected tab.

    I'm trying to figure out a consistent way to catch the change in the active tab and then navigate to that tab's heading after it exists in the document.

    Continue reading...

Compartilhe esta Página