2016-05-06 76 views
0

我有2个组件:CommandListComponentCommandLineComponent。内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阵列成功更新:

enter image description here

谢谢你的帮助。

回答

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... 
    }); 
    } 
} 
+0

我创建一个'CommandLineService'和发送命令到它。它效果很好。但'CommandLineComponent'内的订阅不会触发:[code snippet](http://data3.floomby.com/files/share/6_5_2016/15/rLPNLhsRtEiW0coFxJ0DpA.jpg) – Edward

+0

如何触发事件:'this.commandAdded的.next(命令);'?在引导应用程序时你定义了'CommandLineService'吗? –

+0

我想你不会共享相同的实例... –