Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference of component itself and defined variable in Angular 2

Tags:

angular

dart

How to get a reference of the component "Cart" itself instead of using querySelector() in class Cart?

Also, I want to know is there anyway to access the variable #i from class Cart?

@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>
like image 549
Roger Chan Avatar asked Apr 06 '16 02:04

Roger Chan


1 Answers

@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>
like image 122
Günter Zöchbauer Avatar answered Sep 25 '22 01:09

Günter Zöchbauer