我有2个组件:CommandListComponent
和CommandLineComponent
。在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;
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);
}
}
&#13;
触发click
后,我将选择的命令传递给add
的{{1}}方法:
CommandLineComponent
&#13;
在export class CommandLineComponent {
commands: string[] = [];
add(command: string): void {
if (command) this.commands.push(command);
console.log(this.commands);
}
}
的模板中,我用* ngFor打印一个命令列表:
CommandLineComponent
&#13;
但是当我选择命令并更新了<li *ngFor="#command of commands" class="b-command-textarea__command">{{command}}</li>
的{{1}}数组时,* ngFor不会触发。因此,数据绑定不起作用。 commands
数组成功更新:
感谢您的帮助。
答案 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...
});
}
}