Динамическая ссылочная переменная шаблона внутри ngFor (Angular 2)
Как объявить динамическую ссылочную переменную шаблона внутри ngFor
элемент?
Я хочу использовать компонент popover из ng-bootstrap, код popover (с привязкой Html) выглядит так:
<ng-template #popContent>Hello, <b>{{name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
I've got markup and bindings in my popover!
</button>
Как я могу обернуть эти элементы внутри ngFor
?
<div *ngFor="let member of members">
<!-- how to declare the '????' -->
<ng-template #????>Hello, <b>{{member.name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="????" popoverTitle="Fancy content">
I've got markup and bindings in my popover!
</button>
</div>
Хммм... есть идеи?
1 ответ
Ссылочные переменные шаблона ограничиваются шаблоном, в котором они определены. Структурная директива создает вложенный шаблон и, следовательно, вводит отдельную область видимости.
Таким образом, вы можете просто использовать одну переменную для ссылки на шаблон
<div *ngFor="let member of members">
<ng-template #popupContent>Hello, <b>{{member.name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
I've got markup and bindings in my popover!
</button>
</div>
и он должен работать, потому что он уже объявлен внутри <ng-template ngFor
Для более подробной информации смотрите также:
Это лучшее решение, которое я нашел: /questions/12787907/dostup-k-neskolkim-zritelyam-s-pomoschyu-viewchild/12787909#12787909
В этом ответе они используют:
@ViewChildren('popContent') components:QueryList<CustomComponent>;
Построить список этих динамически генерируемых компонентов. Настоятельно рекомендую проверить это!
Другой способ разрешить это - создать компонент, который обертывает кнопку и ng-template.
<div *ngFor="let member of members">
<popover-button [member]="member"></pop-over-button>
</div>
И в компоненте popover-button укажите следующее:
<ng-template #popContent>Hello, <b>{{member.name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
I've got markup and bindings in my popover!
</button>
Ты можешь использовать trackBy: trackByFn
в *ngFor
<div *ngFor="let member of members;trackBy: trackByF">
<ng-template #popupContent>Hello, <b>{{member.name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
I've got markup and bindings in my popover!
</button>
</div>