angular 2 tabs - access child elements

2019-09-12 01:40发布

问题:

i'm trying to access the html elements inside the tabs component using the example from angular 2 docs: https://angular.io/resources/live-examples/homepage-tabs/ts/plnkr.html Here is my implementation so far:

      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);
    }

}

And the formbuilder.component.html code:

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

Using the above code i can only access the elements outside 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',
    //templateUrl: './app/formbuilder/formbuilder.component.html',
    template: `
    <ui-tabs>
          <template ui-pane title='Overview'>
            <div>test div</div>
            You have 1 details.
          </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() {
      // viewChild is set
       var myDiv: HTMLDivElement = this.testDiv.nativeElement;
       console.log(myDiv);

    }
}

The above example works, but it seems that the element can only be accessed if the current tab has the "active='true'" when the view is initially rendered, otherwise it will give an error. And here is an non working example:

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

So after the ngAfterViewInit(), the element from the active tab called "Summary" will be accessible, but it won't work for the elements for the other tab(s). Any suggestions on how to be able to access the elements on tab change?

回答1:

You could try the following:

@ViewChild('testBox') testDiv:ElementRef;

instead of:

@ViewChild('testDiv') testDiv:ElementRef;

(Or it's a typo in your snippet)