【问题标题】:Angular - Custom Structural Directive - ngForIn: How can I create my own local variable?Angular - 自定义结构指令 - ngForIn:如何创建自己的局部变量?
【发布时间】:2018-06-11 10:00:59
【问题描述】:

希望你能正确理解这一点。

我创建了一个自定义 ngForIn 指令来获取对象的键。这适用于以下代码:

import {Directive, Input, OnChanges, SimpleChange, SimpleChanges} from "@angular/core";
import {NgForOf} from "@angular/common";

@Directive({
    selector: "[ngFor][ngForIn]"
})
export class NgforinDirective<T> extends NgForOf<T> implements OnChanges {

    @Input() public ngForIn: any;

    public ngOnChanges(changes: SimpleChanges): void {
        if (changes.ngForIn) {

            if (this.ngForIn) {
                this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
                const change = changes.ngForIn;
                const currentValue = Object.keys(change.currentValue);
                const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
                changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
            }
            super.ngOnChanges(changes);
        }
    }
}

我现在面临的问题是我需要在模板中多次访问 object[key] 的值。到目前为止,我正在像这样(肮脏)使用它:

<div *ngFor="let key in object">
     {{object[key]}}

但是,我希望能够做这样的事情:

<div *ngFor="let key in object; let value = object[key]">
     {{value}}

我正在阅读 ngForOf 的源代码,因为它包含一些局部变量,例如“index”或“odd”。

我认为解决方案是在自定义指令中创建一个局部变量,该变量将返回当时正在迭代的 object[key] 的值,但我真的不明白我应该怎么做;或者也许有一个我不知道的更简单的解决方案。

有没有人遇到过这样的问题并找到了解决方案?

谢谢!

【问题讨论】:

  • 你可以使用指令中的@Output 发出

标签: javascript angular typescript angular-directive


【解决方案1】:

您已经可以使用*ngFor 做您想做的事。只需使用Object.keys(yourObject) 获取对象的键,然后遍历它们并显示值。

import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let key of keys;">
        {{ key }}: {{ person[key] }}
      </li>
    </ul>
  `,
})
export class App {
  keys: string[];
  person: object;

  constructor() {
    this.person = {
      'First Name': 'Bob',
      'Last Name': 'Smith',
      'Age': 44,
    };
    this.keys = Object.keys(this.person);
  }
}

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App],
})
export class AppModule {}

Plunkr:https://plnkr.co/edit/BOgMT8XYphirNi6kObZv

如果您不想在组件中这样做,您也可以创建一个管道来获取对象键。我不确定访问object[value] 会出现什么问题。

【讨论】:

  • ngForIn 指令已经在工作,无需将对象转换为可迭代对象,因此我可以将 ngFor 与它一起使用。 Object[key] 有效,这是我目前正在使用的,但是为了方便起见,由于它在模板中多次使用,我想以与使用 let i = index 相同的方式使用局部变量,但在这种情况下,我想要类似 let value = object[key]
  • 任何对你有用的东西。似乎需要编写大量代码来多次编写object[key],但这只是我的观点。
  • 我完全理解您的观点,但这是我们正在研究的工作,因为它们习惯于从默认情况下执行此操作的 angularJS 进行 ng-repeat。
  • 明白。有几个建议可以从 Angular Github 上的快速搜索中添加它以帮助进行转换。
  • OP特别提到他想摆脱object[value]语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多