javascript - ngFor 在 Angular2 中更新依赖变量后不会触发

标签 javascript data-binding angular components ngfor

我有 2 个组件:CommandListComponentCommandLineComponent。在 CommandListComponent 模板内部,我处理文本字符串上的单击事件:

CommandListComponent 模板:

<li *ngFor="#command of commandList" class="b-command-list__command"><span (click)="checkCommand(command)" class="b-command-list__text">{{command}}</span></li>

commandlist.component.ts

import {CommandLineComponent} from "./commandline.component";

...

export class CommandListComponent {
    commandLineComponent: any;

    constructor(private _commandLine: CommandLineComponent) {
        this.commandLineComponent = _commandLine;
    }

    checkCommand(command: string): void {
        this.commandLineComponent.add(command);
    }

}

click被触发时,我将选择的命令传递给CommandLineComponentadd方法:

export class CommandLineComponent {
    commands: string[] = [];

    add(command: string): void {
        if (command) this.commands.push(command);
        console.log(this.commands);
    }
}

CommandLineComponent 的模板中,我使用 *ngFor 打印命令列表:

<li *ngFor="#command of commands" class="b-command-textarea__command">{{command}}</li>

但是当我选择一个命令并且更新了 CommandLineComponentcommands 数组时, *ngFor 不会触发。因此,数据绑定(bind)不起作用。 commands 数组更新成功:

enter image description here

感谢您的帮助。

最佳答案

问题在于您引用 commandLineComponent 组件的方式。如果它们之间存在关系,您可以使用 ViewChild 装饰器

class CommandListComponent {
  @ViewChild(CommandLineComponent)
  commandLineComponent: any;
  (...)
}

如果没有,您需要使用共享服务在这两个组件之间共享命令列表。类似这样的事情:

export class CommandService {
  commands:string[] = [];
  commandAdded:Subject<string> = new Subject();

  add(command: string): void {
    if (command) {
      this.commands.push(command);
      this.commandAdded.next(command);
    }
    console.log(this.commands);
  }
}

您需要在引导应用程序时定义服务,并且两个组件都可以注入(inject)它。

class CommandListComponent {
  constructor(private commandService:CommandService) {
  }
}

checkCommand(command: string): void {
    this.commandService.add(command);
}

CommandLineComponent 组件将收到这样的新命令通知,并可以相应地更新 View :

class CommandLineComponent {
  constructor(private commandService:CommandService) {
    this.commandService.commandAdded.subscribe(command => {
      // Update the list displayed in the component...
    });
  }
}

关于javascript - ngFor 在 Angular2 中更新依赖变量后不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073020/

相关文章:

javascript - 如何在不出现引用错误的情况下将不存在的 JavaScript 对象与 undefined object 进行比较?

javascript - 如何自动删除 NodeJs 中超过一周的所有记录/行?

javascript - Body bgcolor 属性权重

javascript - 使用 KnockoutJS 绑定(bind)树结构的正确方法

angular - ng build 时从 nginx 获取 404 Not Found

angular - karma 不断要求更多与测试组件无关的进口

javascript - 如何使 Ember 数据停止根据其规则将我的端点更改为单数和复数?

响应指标的 JavaFX 场景图修改

javascript - 对象的属性未定义,即使对象上的 console.log 显示属性值

c# - 向WPF Datagrid添加很多项目会消耗大量CPU时间