12

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>
4
  • 2
    Can you explain what are you trying to do. You can inject ElementRef into your cart constructor constructor(private _element:ElementRef) to get the Angular2 element wrapper. nativeElement property has to underlying dom Commented Apr 6, 2016 at 2:59
  • Why would you want to access #i, it's a value from items which is available in Cart anyway. Commented Apr 6, 2016 at 3:20
  • Hi Chandermani. Thanks for your helpful hint, it solve my first problem. Commented Apr 6, 2016 at 3:26
  • Hi Günter Zöchbauer. Not only #i. In fact, I want to know anyway can access variables defined in a template? Commented Apr 6, 2016 at 3:29

1 Answer 1

6
@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>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Günter! It is very helpful.
What exactly does "Cart(this._element);" do here?
@Cuel it's like constructor(private _element:ElementRef) in TS
Ah. Lots of nifty stuff :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.