javascript - 如何在 *ngTemplateOutlet 中使用上下文和带有材料表的 Angular 中的自定义指令
问题描述
使用的框架:Angular 8 和 Material Design
我已经制作了一个表格模板,用于在不同的组件中重用我的结构,所以我不必再次重建它。该表可以在每个组件上使用和修改,在桌面视图中它看起来像我预期的那样。现在我添加了一个应该看起来不同的移动标题行,我希望在上下文中使用带有“isMobile”属性的 *ngTemplateOutlet 可以解决我的问题。但是在组件中我只接收数据,而不是上下文!?
有没有人有解决这个问题的想法?
在我的组件中使用了 ng-template,我在其中使用了我的表格组件,但它什么也没显示。使用 ng-container 向我展示了提供的数据。
我的模板表的一部分:
<ng-container matColumnDef="{{ headerValue.field }}-filter" *ngFor="let headerValue of headerValues">
<ng-container *ngIf="headerValue.isSearchable">
<th mat-header-cell *matHeaderCellDef [class.hidden-below-lg]="headerValue.isMobileHeaderRow">
<trp-input-field
formControlName="{{ headerValue.field }}"
placeholder="{{ 'SEARCH' | translate }}"
class="dark"
></trp-input-field>
</th>
<td
mat-cell
*matCellDef="let element"
[class.hidden-below-lg]="headerValue.isMobileHeaderRow"
[innerHTML]="
(element[headerValue.field] ? element[headerValue.field].toString() : '') | translate
"
></td>
</ng-container>
<ng-container *ngIf="!headerValue.isSearchable">
<th mat-header-cell *matHeaderCellDef></th>
</ng-container>
在我的组件中:
<app-table-header
[isSearchable]="true"
name="{{ 'TARGET_AGREEMENT.STORES.FIELDS.NAME' | translate }}"
field="name"
[isMobileHeaderRow]="true"
width="260px"
>
<ng-container *appColumnFormat="let targetAgreement">
{{ targetAgreement.name }} -
{{ targetAgreement.rmsId }}
</ng-container>
</app-table-header>
我的表头指令中使用的 appColumnFormat-Directive
@Directive({
selector: '[appColumnFormat]',
})
export class TableColumnFormatDirective {
}
my table-header-Directive
@Directive({
selector: 'trp-table-header',
})
export class TableHeaderDirective {
@Input() public name: string;
@Input() public field: string;
@Input() public width: string;
@Input() public isSearchable = false;
@Input() public isMobileHeaderRow = false;
@Input() public sorting = (_data: any, _sortHeaderId: string):
string => {
return '';
};
@ContentChild(TableColumnFormatDirective, { static: false, read:
TemplateRef })
public template: TemplateRef<any>;
}
我希望在我的组件中有一个上下文对象,例如 -->
<td mat-cell *matCellDef="let element; let isMobile" [class.hidden-below-lg]="headerValue.isMobileHeaderRow" [innerHTML]="(element[headerValue.field] ? element[headerValue.field].toString() : '') | translate "></td>
or something
一开始我遵循了这个教程: https ://blog.jonrshar.pe/2017/May/29/angular-ng-template-outlet.html
解决方案
尝试这个 :
在您的app-table-header组件的视图中,使用 *ngTemplateOutlet 而不是使用 innerHTML
应用程序表头
<td mat-cell *matCellDef="let element"
[class.hidden-below-lg]="headerValue.isMobileHeaderRow">
<ng-container *ngTemplateOutlet="template; context: { $implicit: element }"></ng-container>
</td>
您在此模板中传递的上下文将渗透到您的结构指令。
推荐阅读
- python - 涉及字符串连接的 Python 列表理解中嵌套的 for 循环细分
- python - 如何将字符串拆分为特定的关键字?
- wordpress - 仅从顶级菜单中删除下拉指示器
- c++ - 使用以 int** 作为成员的结构向量
- amazon-web-services - 无法手动删除 AWS S3 存储桶
- reactjs - 我在减速器中的语法有什么问题?
- java - 如何遍历二维数组并按行主要顺序计算每行中有多少个元素大于1
- django - 使用一个表格行生成每个项目的两个 forloop
- php - 将选择标记值传递给 laravel 框架上的路由 url
- java - 处理写得不好的外部异常的最佳方法?