如何在Angular 2中获取组件本身和定义变量的引用

时间:2016-04-06 02:16:13

标签: dart angular

如何获得组件的参考" Cart"本身而不是在类Cart中使用querySelector()?

另外,我想知道有没有从类Cart中访问变量#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 个答案:

答案 0 :(得分:4)

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