2016-04-04 20 views
0

私は角2つのドキュメントからの例を使用して、タブのコンポーネント内のHTML要素にアクセスしようとしている: https://angular.io/resources/live-examples/homepage-tabs/ts/plnkr.html ここでは、これまでの私の実装です:角度2つのタブ - アクセス子要素

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

} 

そして、 formbuilder.component.htmlコード:私は<template>タグ外の要素にアクセスすることができ、上記のコードを使用

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

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

    } 
} 

上記の例では動作し、現在のタブが「アクティブ= 『真』」ビューが最初にレンダリングされる場合、そうでない場合がある場合要素にのみアクセスすることができると思われますエラーが発生します。 そしてここでは、非作業例です:

<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> 

のでngAfterViewInit()の後に、「要約」と呼ばれるアクティブなタブから要素がアクセスできるようになりますが、それは他のタブの要素のために動作しません。 (s)。タブ上の要素にアクセスする方法についての提案は変わりますか?

+1

それが動作するはずです:http://plnkr.co/edit/wGrjfZIOslqwXUPI6mly?p = preview –

答えて

0

あなたが次のことを試みることができる:

@ViewChild('testBox') testDiv:ElementRef; 

の代わり:

@ViewChild('testDiv') testDiv:ElementRef; 

(または、それはあなたのスニペットのタイプミスです)

+0

はい、タイプミスでした。 – Crashoveride

+0

さて、あなたのコードにテンプレートタグが必要なのはなぜですか?これはAngularによって使用されるものです。 –

+0

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template –