【问题标题】:Does Angular2 have a built-in concept of ngInit from Angular1?Angular2 是否具有来自 Angular1 的 ngInit 的内置概念?
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2013-02-25
    • 2019-03-14
    相关资源
    最近更新 更多