2016-04-06 9 views
1

CartクラスでquerySelector()を使用する代わりに、コンポーネント "Cart"自体の参照を取得するにはどうすればよいですか?コンポーネント2の参照と角2の変数の定義方法

また、クラスカートから変数#iにアクセスする方法はありますか?

@Component(
    selector: '[cart]', 
    templateUrl: 'cart.html') 
class Cart { 

    handling(){ 
     querySelector("div[cart]"); 
    } 
} 

<div cart> 
    <ul> 
     <li *ngFor="#i of items.values">{{i}}</li> 
    </ul> 
</div> 
+1

あなたがやろうとしているかを説明することができます。 ElementRefをCartコンストラクタの 'constructor(private _element:ElementRef)'に挿入して、Angular2要素ラッパーを取得することができます。 nativeElementプロパティが基底のDOMにある – Chandermani

+0

なぜ '#i'にアクセスしたいのですが、それは' items'の値で 'Cart'でも利用可能です。 –

+0

こんにちはチャンドラーニ。 あなたの役に立つヒントのおかげで、それは私の最初の問題を解決します。 –

答えて

3
@Component(
    selector: '[cart]', 
    templateUrl: 'cart.html') 
class Cart implements AfterViewInit { 
    // as mentioned by @Chandermani 
    ElementRef _element; 
    Cart(this._element); 

    @ViewChildren('myLi') ElementRef myLis; 
    // or for a single element or just the first one 
    // @ViewChild('myLi') ElementRef myLi; 

    ngAfterViewInit() { 
     // not initialized before `ngAfterViewInit()` 
     print(myLis); 
    } 

    handling(){ 
     querySelector("div[cart]"); 
    } 
} 

<div cart> 
    <ul> 
     <li #myLi *ngFor="let i of items.values">{{i}}</li> 
    </ul> 
</div> 
+1

ありがとうGünter!非常に役に立ちます。 –

+0

「カート(this._element);」とは正確に何ですか?ここでやる? – Cuel

+0

@CuelそれはTS –

関連する問題