【发布时间】:2017-05-19 09:57:01
【问题描述】:
我编写了一个 angular2 结构指令,它类似于 angular 1 中的 ng-init。本质上,它允许将当前上下文中的复杂表达式别名为子上下文中的单个变量。
Angular2 有没有内置的方法来做到这一点,我错过了?
我不是在寻找如何将逻辑移动到我的组件中的解释,而是如何在每次使用时不复制/粘贴的情况下将表达式保留在 html 中。
没有 ngInit:
<div>
<span>{{ getSlot(locationX, locationY).name }}</span>
<span>{{ getSlot(locationX, locationY).product }}</span>
</div>
使用 ngInit:
<div *ngInit="let slot be getSlot(locationX, locationY)">
<span>{{ slot.name }}</span>
<span>{{ slot.product }}</span>
</div>
自定义结构指令:
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core';
@Directive({
selector: '[ngInit]'
})
export class ngInit {
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef<any>) { }
@Input() set ngInitBe(value: any) {
this._viewContainer.clear();
this._viewContainer.createEmbeddedView(this._templateRef, { $implicit: value });
}
}
【问题讨论】:
-
getSlot来自哪里? -
抱歉,我没有包含其他看起来不太相关的代码。 getSlot 是我组件上的一个函数。 locationX 和 locationY 是来自 2 个外部 *ngFor 的 $implicit 变量。
标签: angular angular2-template angular2-directives