我有 2 个组件:CommandListComponent
和 CommandLineComponent
。在 CommandListComponent
模板内部,我处理文本字符串上的单击事件:
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
被触发时,我将选择的命令传递给CommandLineComponent
的add
方法:
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>
但是当我选择一个命令并且更新了 CommandLineComponent
的 commands
数组时, *ngFor 不会触发。因此,数据绑定(bind)不起作用。 commands
数组更新成功:
感谢您的帮助。
最佳答案
问题在于您引用 commandLineComponent
组件的方式。如果它们之间存在关系,您可以使用 ViewChild
装饰器
class CommandListComponent {
@ViewChild(CommandLineComponent)
commandLineComponent: any;
(...)
}
如果没有,您需要使用共享服务在这两个组件之间共享命令
列表。类似这样的事情:
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);
}
}
您需要在引导应用程序时定义服务,并且两个组件都可以注入(inject)它。
class CommandListComponent {
constructor(private commandService:CommandService) {
}
}
checkCommand(command: string): void {
this.commandService.add(command);
}
CommandLineComponent
组件将收到这样的新命令通知,并可以相应地更新 View :
class CommandLineComponent {
constructor(private commandService:CommandService) {
this.commandService.commandAdded.subscribe(command => {
// Update the list displayed in the component...
});
}
}
关于javascript - ngFor 在 Angular2 中更新依赖变量后不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073020/