ngFor根据Angular2中的变量更新后不会触发

时间:2016-05-06 12:55:55

标签: javascript data-binding angular components ngfor

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

CommandListComponent模板:



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

commandlist.component.ts

&#13;
&#13;
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);
    }

}
&#13;
&#13;
&#13;

触发click后,我将选择的命令传递给add的{​​{1}}方法:

&#13;
&#13;
CommandLineComponent
&#13;
&#13;
&#13;

export class CommandLineComponent { commands: string[] = []; add(command: string): void { if (command) this.commands.push(command); console.log(this.commands); } }的模板中,我用* ngFor打印一个命令列表:

&#13;
&#13;
CommandLineComponent
&#13;
&#13;
&#13;

但是当我选择命令并更新了<li *ngFor="#command of commands" class="b-command-textarea__command">{{command}}</li>的{​​{1}}数组时,* ngFor不会触发。因此,数据绑定不起作用。 commands数组成功更新:

enter image description here

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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

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

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

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);
  }
}

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

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

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

CommandLineComponent组件会收到类似这样的新命令的通知,并可以相应地更新视图:

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