3

でクエリを実行するために、同じ名前のテンプレート参照変数を使用したいと考えています@ViewChildren

メタデータのプロパティ:

selector - クエリに使用されるディレクティブ タイプまたは名前。
read - クエリされた要素から別のトークンを読み取ります。

しかし、テンプレート解析エラーが発生しました:

Reference "#abc" is defined several times

サンプル:

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);
  }
}

質問:
1. テンプレート内で同じ名前のテンプレート参照変数を定義できますか? 2.名前を個別に定義せずに、同じセレクター
を使用して複数の要素を照会する方法は?

4

1 に答える 1