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

Rog*_*han 7 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>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

@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>
Run Code Online (Sandbox Code Playgroud)

  • @Cuel 就像 TS 中的 `constructor(private _element:ElementRef)` (2认同)