[英]Is it possible to use the same template reference variable for different elements?
Consider this case, where the two different divs never exist at the same time: 考虑这种情况,两个不同的div永远不会同时存在:
<!-- Mutually exclusive containers -->
<ng-container *ngIf="predicate">
<div #myRef>
...
</div>
</ng-container>
<ng-container *ngIf="!predicate">
<div #myRef>
...
</div>
</ng-container>
And, in my component: 而且,在我的组件中:
@ViewChild('myRef', {read: ElementRef}) private myRef: ElementRef;
// do something with myRef...
Yes you can have. 是的,你可以拥有。 Even if you have 2 same template ref in your template, if you try to fetch using @ViewChild then you will get the first ref.
即使您的模板中有2个相同的模板引用,如果尝试使用@ViewChild进行获取,您也会获得第一个引用。
<ng-container >
<div #myRef>
<p> this is the first content, </p>
</div>
</ng-container >
<ng-container >
<div #myRef>
<p> this is the Seoncd content, </p>
</div>
</ng-container >
@ViewChild('myRef') myRef;
ngAfterViewInit(): void {
console.log(this.myRef.nativeElement);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.