本文介绍了如何在单独的文件中加载ng-template?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我像下面一样使用了ng-template,它工作正常.

In below sample, I have used ng-template like below and it is working fine.

<ng-template #template let-dataSource="">
  <span *ngIf="dataSource.iconCss" class="e-menu-icon {{dataSource.iconCss}}"></span> {{dataSource.header}} {{dataSource.text}}
  <span *ngIf="dataSource.templateHeader" class="e-login-content">
        <button ejs-button cssClass="e-info">Sign In</button>
      </span>
</ng-template>

但是我想为ng-template 内容创建一个新文件,并且希望在另一个文件中使用它.我已经尝试过以下方法,但无法正常工作.请帮助我找到这种情况的解决方案.

But I want to create a new file for ng-template content and I want to use it in another file. I have tried like below but not working. Please help me find a solution for this case.

<ng-template #template let-dataSource="">
  <span *ngIf="dataSource.iconCss" class="e-menu-icon {{dataSource.iconCss}}"></span>
  {{dataSource.header}} {{dataSource.text}}
  <span *ngIf="dataSource.templateHeader" class="e-login-content">
    <button ejs-button cssClass="e-info">Sign In</button>
  </span>
</ng-template>
<div class="control-section">
  <ejs-menu #menu [items]='dataSource' [fields]='menuFields'>
    <ng-container *ngTemplateOutlet="template;"></ng-container>
  </ejs-menu>
</div>

ref stackoverflow问题: angular2 ng-template在单独的文件中

ref stackoverflow question: angular2 ng-template in a separate file

推荐答案

我从github angular得到了这个问题的答案请检查此 https://github.com/angular/angular/issues/27503

i got an answer for this question from github angularplease check this https://github.com/angular/angular/issues/27503

答案:

我已经将模板初始化为新组件,如下所示

i have initialized my template as a new component as like below

template.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-device',
  template: `
  <span *ngIf="dataSource.iconCss" class="e-menu-icon {{dataSource.iconCss}}"></span>
  {{dataSource.header}} {{dataSource.text}}
  <span *ngIf="dataSource.templateHeader" class="e-login-content">
    <button ejs-button cssClass="e-info">Sign In</button>
  </span>
`
})
export class DeviceComponent {
  @Input()
  dataSource: any;
}

然后我在父级组件中使用了该组件模板,如下所示

default.html

<div class="control-section">
	<ejs-menu #menu [items]='dataSource' [fields]='menuFields'>
    <ng-template #template let-dataSource>
      <app-device [dataSource]="dataSource"></app-device>
    </ng-template>
  </ejs-menu>
</div>

这篇关于如何在单独的文件中加载ng-template?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:23