我有2个组件:CommandListComponent
和CommandLineComponent
。内CommandListComponent
模板,我处理的文本字符串click事件:ngFor在Angular2更新依赖变量后不会触发
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
被激发我通过choosen命令add
方法CommandLineComponent
的:
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>
但是* ngFor不会在我选择命令时触发,commands
阵列的CommandLineComponent
已更新。所以,数据绑定不起作用。 commands
阵列成功更新:
谢谢你的帮助。
我创建一个'CommandLineService'和发送命令到它。它效果很好。但'CommandLineComponent'内的订阅不会触发:[code snippet](http://data3.floomby.com/files/share/6_5_2016/15/rLPNLhsRtEiW0coFxJ0DpA.jpg) – Edward
如何触发事件:'this.commandAdded的.next(命令);'?在引导应用程序时你定义了'CommandLineService'吗? –
我想你不会共享相同的实例... –