【问题标题】:How does the implementation of a scoped variable work in *ngFor作用域变量的实现如何在 *ngFor 中工作
【发布时间】:2019-06-17 21:04:52
【问题描述】:

在 Angular 中,我们可以通过以下方式使用 *ngFor

<li *ngFor="let hero of heroes">
  {{ hero }}
</li>

但是Angular如何定义作用域变量hero 我能实现同样的事情吗? 我只对作用域变量感兴趣,对循环部分不感兴趣。

【问题讨论】:

    标签: javascript angular scope angular2-directives angular-directive


    【解决方案1】:

    component.ts 中定义的所有公共变量(函数)都可以从 component.html 访问,并且可以使用 interpolation and template expresion 显示

    当你有一个*ngFor,当你定义“让数组的变量”时,变量是可访问的inside *ngFor并且是数组的每个元素

    如果要声明变量,请使用ng-if-let,例如

    <div *ngIf="'hello word' as greeting">
      {{greeting}}
    </div>
    

    【讨论】:

    • 很抱歉,我认为您的问题有误。看看我的解决方案,这样你就可以理解我的问题了。
    • 对不起我的回答,我更新了。你在找 ng-if-let 吗?
    • 我只是在寻找一种将作用域变量从“组件”(本例中为指令)传递给其子级的方法
    【解决方案2】:

    好的,我能够解决我的问题。我没有意识到我自己可以使用以下语法:

    *ngFor="let test...."
    

    有了这个,我能够创建以下指令:

    import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[appWrapper]',
    })
    export class WrapperDirective {
      constructor(viewContainer: ViewContainerRef, template: TemplateRef<any>) {
        viewContainer.createEmbeddedView(
          template,
          { ['$implicit']: 'Max Mustermann' },
          0,
        );
      }
    }
    

    这个指令现在可以像这样使用:

    <div *appWrapper="let name">{{ name }}</div>
    

    有没有办法摆脱 let name 部分?

    This Stackoverflow post helped me to implement my idea

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 2012-09-20
      • 2013-05-27
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多