[英]How to load the ng-template in separate file?
在下面的示例中,我使用了如下所示的ng-template
並且它工作正常。
示例鏈接: 點擊這里
<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
內容創建一個新文件,我想在另一個文件中使用它。 我已經嘗試過如下所示但沒有工作。 請幫我找到這個案例的解決方案。
模板.html
<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>
默認.html
<div class="control-section"> <ejs-menu #menu [items]='dataSource' [fields]='menuFields'> <ng-container *ngTemplateOutlet="template;"></ng-container> </ejs-menu> </div>
樣本 2: 樣本 2
參考 stackoverflow 問題: 單獨文件中的 angular2 ng-template
您可以為模板創建一個組件(將其命名為tplComponent
),然后在其中創建tplComponent
模板。 然后在其他組件中,獲取tplComponent
的實例並從中獲取模板。 這是一個問題 ,有一個這種方法的例子(雖然我沒有嘗試過)。
如果有效,請告訴我。
我不認為你應該有這樣的模板。 只需創建一個經典組件,如果您需要模板引用,請將其包裝在ng-template
。
我從github angular得到了這個問題的答案請檢查這個https://github.com/angular/angular/issues/27503
回答:
步驟1:
我已將模板初始化為新組件,如下所示
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>
示例鏈接示例單擊我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.