2

Consider this case, where the two different divs never exist at the same time:

<!-- 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...
4
  • 6
    Did you try it? Commented Sep 4, 2018 at 13:22
  • 2
    Yes, it is possible. You can even use the same variable for elements that are present at the same time, as shown in this answer. Commented Sep 4, 2018 at 13:25
  • 1
    Sure I tried it. I was wondering whether it was advised against. Sorry, I should have specified. Commented Sep 5, 2018 at 8:04
  • 1
    another use case would be to have n no. of elements with same template ref variable and access them in your component class like this @ViewChildren('myRef', {read: ElementRef}) allMyRefs: QueryList<ElementRef>; Commented Nov 27, 2019 at 8:33

1 Answer 1

2

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.

<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 >

enter image description here

 @ViewChild('myRef') myRef;

  ngAfterViewInit(): void {
    console.log(this.myRef.nativeElement);
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.