gpt4 book ai didi

Angular 一次在多个地方使用相同的 TemplateRef - 克隆 TemplateRef?

转载 作者:行者123 更新时间:2023-12-03 17:31:33 27 4
gpt4 key购买 nike

我正在尝试构建一个多选组件,它可以为每个选择选项元素提供一个模板。它大部分都在工作,模板是从选项组件中的 ng-content 中获取的,并显示在“选择弹出框”中。

Options display fine

尝试在选择组件中显示所选选项时遇到问题。好像模板一次只能显示在一个地方,所以当select的选项显示在select中时,就从popover中移除了。

Options display wrong

有什么方法可以克隆 TemplateRef 组件吗?我实际上并不介意模板的上下文是否更新,因为我目前没有使用其中的任何内容,只是模板。

为了清楚起见,包括下面的一些代码片段,我认为没关系。

somepage.component.html 中的用法:

<my-select [(value)]="vals">
<my-option *ngFor="let x of [1,2,3]" [value]="x">Option {{x}}</my-option>
</my-select>`

我的选择.component.html
...
<ng-container [ngTemplateOutlet]="getSelectedOptionTemplate()"></ng-container>
...

我的选择.component.ts
getSelectedOptionTemplate(){
// Some way to clone here could solve the issue?
return this.getSelectedOption().template;
}

我的选择覆盖.component.html
...
<ng-container *ngFor="let opt of options;">
<ng-container [ngTemplateOutlet]="getTemplate(opt)"></ng-container>
</ng-container>
...

我的选项.component.html
<ng-template>
<ng-content></ng-content>
</ng-template>

我的选项.component.ts
...
@ViewChild(TemplateRef)
template: TemplateRef<any>;
...

最佳答案

我在 Github 上找到了这个问题的解决方案。
似乎使用相同的TemplateRefng-template 时工作正在包装组件 包含 ng-content .
想象一下,我们需要获得类似的东西:

<ng-template>
<my-option>
... option content ...(<ng-content></ng-content>)
</my-option>
</ng-template>`
为了得到上面的结构,我们可以实现一个 structural directive .从文档:

Angular transforms the asterisk in front of a structural directiveinto an <ng-template> that surrounds the host element and itsdescendants.


结构指令的代码是:
@Directive({
selector: "[appOptionTemplate]"
})
export class OptionTemplateDirective {
@Input("appOptionTemplate")
value: any;

constructor(
public templateRef: TemplateRef<any>
) {}
}
(注意以下几点:
  • 注入(inject)templateRef在构造函数中
  • Input属性(property))

  • 填充选择选项时,我们将使用以下内容:
    <app-select>
    <ng-container *ngFor="let x of [1,2,3]; let i=index;">
    <app-option *appOptionTemplate="x">
    Option {{x}}
    </app-option>
    </ng-container>
    </app-select>
    现在,我们将使用结构指令来查询 select 中的内容。零件:
    @ContentChildren(OptionTemplateDirective)
    options: QueryList<OptionTemplateDirective>;
    为了显示该选项,我们将使用:
    <ng-container *ngTemplateOutlet="option.templateRef"></ng-container>
    示例:
    https://stackblitz.com/edit/angular-ivy-pues8t

    Github 话题:
    https://github.com/angular/angular/issues/37995

    有关结构指令的更多信息:
    https://angular.io/guide/structural-directives

    关于Angular 一次在多个地方使用相同的 TemplateRef - 克隆 TemplateRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53064929/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com