Angular2是否有来自Angular1的内置ngInit概念?

时间:2017-01-04 23:53:53

标签: angular angular2-template angular2-directives

我编写了一个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 });
    }
}

1 个答案:

答案 0 :(得分:0)

到目前为止我发现的最接近的是这个,但它可能不是预期的目的,因为它有点复杂。

            <template #test>
                <span>{{slot.locationX}}</span>
                <span>{{product.name}}</span>
            </template>

            <template [ngOutletContext]="{ slot: getSlot(locationX, locationY), product: { name: 'a' } }" [ngTemplateOutlet]="test">
            </template>