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

Angular 是否可以对不同的元素使用相同的模板引用变量?,angular,Angular,考虑这种情况,两个不同的div永远不会同时存在: <!-- Mutually exclusive containers --> <ng-container *ngIf="predicate"> <div #myRef> ... </div> </ng-container> <ng-container *ngIf="!predicate"> <div #myRef> ... &l

考虑这种情况,两个不同的div永远不会同时存在:

<!-- Mutually exclusive containers -->

<ng-container *ngIf="predicate">
  <div #myRef>
    ...
  </div>
</ng-container>

<ng-container *ngIf="!predicate">
  <div #myRef>
    ...
  </div>
</ng-container>
是的,你可以。 即使您的模板中有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 >

你试过了吗?是的,有可能。您甚至可以对同时存在的元素使用相同的变量,如中所示。我确实尝试过。我想知道是否有人建议不要这样做。很抱歉,我应该指定。另一个用例是有n个元素具有相同的模板ref变量,并在组件类中访问它们,就像这样
@ViewChildren('myRef',{read:ElementRef})allMyRefs:QueryList
<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);
  }