Template parse errors: Reference "#XXX" is defined several times in angular

Viewed 1995

I want to use the same name of template reference variables for querying at @ViewChildren.

Metadata Properties:

selector - the directive type or the name used for querying.
read - read a different token from the queried elements.

But, I got a template parse error:

Reference "#abc" is defined several times

Sample:

import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren, ElementRef} from '@angular/core';

@Directive({selector: 'pane'})
export class Pane {
  @Input() id: string;
}

@Directive({selector: 'pane1'})
export class Pane1 {
  @Input() id: string;
}

@Component({
  selector: 'app-root',
  template: `
    <span #abc id="1"></span>
    <pane1 #abc id="2"></pane1>
    <pane #abc id="3" *ngIf="shouldShow"></pane>
    <button (click)="show()">Show 3</button>
    <button (click)="hide()">Hide 3</button>

    <div>panes: {{serializedPanes}}</div> 
  `,
})
export class ViewChildrenComp implements AfterViewInit {
  @ViewChildren('abc') panes: QueryList<ElementRef>;
  serializedPanes: string = '';

  shouldShow = false;

  show() { this.shouldShow = true; }
  hide() { this.shouldShow = false; }

  ngAfterViewInit() {
    this.calculateSerializedPanes();
    this.panes.changes.subscribe(
      (r) => {
      this.calculateSerializedPanes(); 
    });
  }

  calculateSerializedPanes() {
    setTimeout(
      () => {
        this.serializedPanes = this.panes.map(p => p.nativeElement.id).join(', '); 
      }, 0);
  }
}

Question:
1. Whether I can define template reference variables with same name in template?
2. How to query multiple elements using the same selector, not defining names individually?

1 Answers
Related