>我创建了一个子组件,并在根组件中多次使用。现在的问题是,当我更新其中一个组件中的变量值时,更改会反映在所有其他相同的组件中。我该如何阻止它?我无法理解这里发生了什么!
请找到该问题的堆栈闪电战
根组件中的根组件 HTML
<hello></hello>
<hello></hello>
你好组件 HTML
<div class="green-box" *ngIf="green; else red"></div>
<ng-template #red>
<div class="red-box"></div>
</ng-template>
<button (click)='changeColor()'>Change Color</button>
你好组件 TS
export class HelloComponent implements OnInit {
green: boolean = true;
constructor(
private changeService: ChangeService,
) {
}
ngOnInit() {
this.changeService.change$.subscribe((data: boolean) => {
this.green = data;
});
}
changeColor() {
this.changeService.changeColor(!this.green);
}
}
更改服务 TS
export class ChangeService {
public changeSubjcet = new Subject();
public change$ = this.changeSubjcet.asObservable();
changeColor( value ) {
this.changeSubjcet.next( value );
}
}
扩展我的评论
这是单一实例服务的定义。存在一个和 应用中只有一个可观察
change$
实例。所以如果你 在某个地方修改它,它会反映在每个人身上 订阅。
如果您希望具有特定于实例的变量,只需创建与任何单一实例服务无关的成员变量。
hello.component.ts
export class HelloComponent {
green: boolean = true;
changeColor() {
this.green = !this.green;
}
}
我已经修改了你的堆栈闪电战。
如果你是Angular的新手,我也建议你学习本教程。它介绍了一些基础知识。