2016-05-06 49 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

我想你不會共享相同的實例... –