加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 检索与TemplateRef关联的变量的名称

发布时间:2020-12-17 17:09:14 所属栏目:安全 来源:网络整理
导读:说我有这个模板: div class="main__container" ng-template #test/ng-template ng-template #test2/ng-template/div 我通过以下方式检索对所有TemplateRef的引用: @ViewChildren(TemplateRef)private templates; 对于所有这些,我如何检索相关变量的名称?
说我有这个模板:

<div class="main__container">
    <ng-template #test></ng-template>
    <ng-template #test2></ng-template>
</div>

我通过以下方式检索对所有TemplateRef的引用:

@ViewChildren(TemplateRef)
private templates;

对于所有这些,我如何检索相关变量的名称?因此,对第一个模板进行“测试”,对另一个模板进行“test2”.我不是绝对想要使用变量,如果可以使用ng-template的属性,那就没关系.我尝试使用TemplateRef,ViewContainerRef和ElementRef,但每次都会返回对comment元素的引用.

解决方法

我设法使用TemplateRef的私有API来做到这一点.这是我目前使用的功能:

@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;

getTemplate(id: string): TemplateRef<any> {
    // FIXME: Should not use private API...
    return this.templates ? this.templates.find((template: any) => 
    template._def.references[id]) : null;
}

但这不适用于生产构建,实际上我发现你的帖子正在寻找另一个解决方案,如果我找到了某些内容或者向Angular github提交功能请求,我会更新.
与此同时,我认为值得分享.

– 编辑 –
看起来确实存在使用结构指令的可能解决方案.

You’ll learn in this guide that the asterisk (*) is a convenience notation and the string is a microsyntax rather than the usual template expression. Angular desugars this notation into a marked-up <ng-template> that surrounds the host element and its descendents. Each structural directive does something different with that template.

Link to documentation

– 编辑2 –
好吧,它适用于检索TemplateRef的指令,但是目前我使用id将其注册到服务,我不再使用ViewChildren / ContentChildren了.使用* ngTemplateOutlet指令的My Component然后使用该服务检索TemplateRef.

这是指令源代码:

@Directive({
     selector: '[formeTemplate]'
})
export class FormeTemplateDirective {
    @Input('formeTemplate') templateId;

    constructor(private host: TemplateRef<any>,private service: FormeTemplateService) { }

    ngOnInit() {
        this.service.register(this.templateId,this.host);
    }
}

服务 :

@Injectable()
export class FormeTemplateService {
    private templates: Array<FormeTemplate>;

    constructor() {
        this.templates = new Array();
    }

    register(id: string,ref: TemplateRef<any>) {
        this.templates.push(new FormeTemplate(id,ref));
    }

    getTemplateRef(templateId: string) : TemplateRef<any> {
        let template = this.templates.find((template) => template.id === templateId);
        return template ? template.ref : null;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读