我有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'嗎? –
我想你不會共享相同的實例... –