如何在HTML模板中使用let?

时间:2018-07-17 05:57:09

标签: html angular let

我正在尝试做一些应该很简单的事情: 我想在* 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>

2 个答案:

答案 0 :(得分:0)

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

指令

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>

答案 1 :(得分:0)

只想提一个非常有效的替代解决方案:

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