简体   繁体   English

是否可以对不同元素使用相同的模板引用变量?

[英]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.

相关问题 在 Angular 11 中投影内容时,是否可以获得对模板变量标识的元素的引用? - When projecting contents in Angular 11, is it possible to get a reference to elements identified by a template variable? 是否可以在茉莉花测试中获取模板引用变量? - Is it possible to get template reference variable in jasmine test? 如何使用输入的Angular模板引用变量来绑定具有相同格式的特定按钮 - How to use Angular template reference variable of input to bind particular button which have the same format 有没有办法在Angular 4中使用“模板引用变量”? - Is there a way to use a “template reference variable” with Angular 4? 在2个组件中使用相同的选择器,但使用不同的模板语法? - Use same selector in 2 components but different template syntax? 如何为* ngFor中的项目创建不同的模板参考变量 - How to create different template reference variable for items in *ngFor angular 角度2模板参考变量 - angular 2 template reference variable Angular 模板变量引用 - Angular template variable reference 是否可以使用由不同版本的 Angular 构建的不同角度元素 - Is it possible to use different angular elements built with different versions of Angular Angular 6:如何使用模板引用变量来调用子方法? - Angular 6: How to use template reference variable for calling child method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM