【问题标题】:How to use let in an HTML template?如何在 HTML 模板中使用 let?
【发布时间】:2018-12-24 17:30:34
【问题描述】:

我正在尝试做一些应该很简单的事情: 我想在 *ngFor 中执行一个函数。该函数返回一个对象。我想在一种“let”语句中设置对象,这样我就可以在 HTML 中使用它的属性:

<div *ngFor="let productGroup of getproductGroupBySomeVariable(variable)">
            <!-- This is where I need to set a variable with the output of 
             the getProductBySomeProperty function-->
      <div *ngLet="'{{getProductBySomeProperty(productGroup.someproperty)}}' 
              as  myVar" class="ui-g">
              <!-- Here I want to use and display the properties of the 
                object created by the function above-->
            <span>{{myVar.property1}} </span>
            <span>{{myVar.property2}} </span> etc....
      </div>
</div>

【问题讨论】:

  • 你不会想在模板中使用这样的函数。它将在每次更改检测时触发。
  • @AJT_82 - 你是对的 - 我把它全部收集成组件网中的数据结构

标签: html angular let


【解决方案1】:

您可以为此创建一个指令,并以这种方式使用它:

指令

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface ILetContext<T> {
    ngLet: T;
}

@Directive({
    selector: '[ngLet]'
})
export class LetDirective<T> {
    private context: ILetContext<T> = { ngLet: undefined };

    constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef<ILetContext<T>>) {
        viewContainer.createEmbeddedView(templateRef, this.context);
    }

    @Input()
    private set ngLet(value: T) {
        this.context.ngLet = value;
    }
}

HTML

<ng-container *ngLet="getproductGroupBySomeVariable(variable) as productGroup;"></ng-container>

【讨论】:

    【解决方案2】:

    只想提一个效果很好的替代解决方案:

    • 单次订阅
    • 适用于虚假值
    • 是强类型
    <ng-container *ngIf="{ user: user | async } as context"> <!-- always true -->
        {{ context.user }}
    </ng-container>
    

    【讨论】:

    • 当数据是假的时,有时你不想在模板中隐藏东西。您已经评论说,在这种情况下,用户 observable 始终是正确的……这是您在打字稿代码中所做的事情,对吗?如果是这样,我认为一个不依赖于打字稿代码的指令值得额外的工作来拥有自己的指令。
    • 你可以随时检查context.user == null,因为它是假的或正在加载的null
    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多