如何获得组件的参考" 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>
答案 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>