Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation:

      import {Component, ElementRef, Inject, OnInit,ViewChild, AfterViewInit} from 'angular2/core';
import {UiTabs, UiPane} from './tabs.component';


@Component({
    selector: 'form-builder',
    templateUrl: './app/formbuilder/formbuilder.component.html',
    directives: [UiTabs, UiPane]
})

export class FormBuilderComponent implements AfterViewInit {
  @ViewChild('testDiv') testDiv:ElementRef;
  ngAfterViewInit() {
      // viewChild is set
       var myDiv: HTMLDivElement = this.testDiv.nativeElement;
       console.log(myDiv);
    }

}

Below is the code snippet from formbuilder.component.html:

<template ui-pane title='Add'>
  <div class="moving-box" #testDiv>
    Drag this box around
  </div>
</template>

Despite the above code, I could only access elements outside of the <template> tag.

UPDATE 1:

import {Component, ElementRef, Inject, OnInit,ViewChild, AfterViewInit,ViewEncapsulation} from 'angular2/core';
import {UiTabs, UiPane} from './tabs.component';


@Component({
    selector: 'form-builder',
    template: `
    <ui-tabs>
          <template ui-pane title='Overview'>
            <div>test div</div>
            You have 1 detail.
          </template>
          <template ui-pane title='Summary' active="true">
            <div #testDiv>second div</div>
          </template>
        </ui-tabs>
    `,
    directives: [UiTabs, UiPane],
})

export class FormBuilderComponent implements AfterViewInit {
  @ViewChild('testDiv') testDiv:ElementRef;
  ngAfterViewInit() {
       var myDiv: HTMLDivElement = this.testDiv.nativeElement;
       console.log(myDiv);

    }
}

The updated example works, but it appears that the element can only be accessed if the current tab has the "active='true'" attribute when the view is initially rendered, otherwise it will result in an error. An example where this does not work is as follows:

    <ui-tabs>
      <template ui-pane title='Overview'>
        <div #testDiv>first tab div</div>
        You have 1 detail.
      </template>
      <template ui-pane title='Summary' active="true">
        <div #testDiv1>second tab div</div>
      </template>
    </ui-tabs>

After the ngAfterViewInit(), the element from the active tab named "Summary" will be accessible, but it won't work for elements in other tabs. Any suggestions on how to access elements on tab change?

Answer №1

Here is a suggestion to consider:

@ViewChild('tryBox') tryDiv:ElementRef;

Rather than using:

@ViewChild('tryDiv') tryDiv:ElementRef;

(Could be a mistake in the code snippet)

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

How can I optimize my Javascript applications for better search engine rankings?

Recently, I've been exploring the idea of implementing a fresh workflow process for web development. Yemoan, Grunt, and Bower in conjunction with AngularJS look promising as a solution for front-end development. However, one major drawback is their po ...

What is the best method to retrieve information from two tables on a webpage that have identical classes?

I am facing a challenge in retrieving or selecting data from two different tables that share the same class. My attempts to access this information using 'soup.find_all' have proven to be difficult due to the formatting of the data. There are m ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

I am currently running the most recent version of AngularFire2. Is there a way to revert back to the earlier version?

Encountering errors with the syntax of the old angularfire2 version while using the latest version (angularfire2 version 4.0.0) pushed me to consider downgrading to a lower version (angularfire2 version 2.0.0). Is there a specific way to do this without ...

Combining the powers of Javascript and Drupal can create

My current setup includes an "open video" button and a form that triggers an ajax call to render files with the corresponding buttons when users click on handouts or videos. I have encountered a problem: Whenever I click on "open the video" after renderi ...

Troubleshooting steps for resolving a node.js error during execution

I recently delved into server side programming with node.js, but I'm encountering some issues when trying to execute it. My server is set up at 127.0.0.1:80, however, I keep running into errors. Console: Server running at http://127.0.0.1:80/ node:ev ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...

Error code 302 is triggered when attempting to retrieve an HTML file from a web address

I'm having trouble retrieving the HTML document from the URL provided below: The issue is that I keep getting a 302 response code! I am not very familiar with how this request is being handled (with the function and parameters), so I am unsure of the ...

Step-by-step guide on dynamically generating table rows in React

I have been trying to dynamically create a table with rows and columns based on an array. While my rest request is functioning properly, I am facing challenges when attempting to switch from a hard-coded example to a dynamic approach using loops or mapping ...

Initiating a Page with Dynamic Modal Window according to Backend Exigencies

Dear experts, can you help me with a problem? I want to implement a modal window on an vb.aspx page if a specific condition from the codebehind query is true. How can I achieve this? Thank you! ...

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Why is the validate function not being executed in the Backbone Model?

I am a beginner in learning Backbone and I am attempting to implement simple validation in my Person Model. However, I am facing an issue where the validate method does not run when I set a new age. Can someone guide me on where I might be making a mistake ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

Can a file be successfully retrieved using an HTTP POST request?

Can a file be downloaded using HTTP POST method? I am aware of the "Get" method (windows.location), but in my scenario, there are many parameters that need to be sent to the server. ...

Basic draggable pop-up window using HTML5 for a seamless experience

Can anyone provide me with helpful resources or tutorials to create a draggable popup using HTML5 without jQuery? I want to keep it simple and avoid external libraries like jQuery UI. Currently, I have an absolutely positioned div that looks like a popup ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...