我想使用同名的模板引用变量在@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. 如何使用同一个选择器查询多个元素,而不是单独定义名称?