gpt4 book ai didi

javascript - Angular 2 更改检测,ngClass 模型由同级组件更新,但模板未刷新

转载 作者:行者123 更新时间:2023-12-03 06:25:27 25 4
gpt4 key购买 nike

我的设置是这样的:

ma​​in.ts - 常规结构,没有问题

app.component.ts - 常规结构,没有问题

app.component.html

<navigation-cart></navigation-cart>
<div id="content">
... other stuff ...
<start-arrow></start-arrow>
</div>

ui-layout.service.ts - 此服务负责打开和关闭应用程序中的所有区域。

import {Injectable} from '@angular/core';

@Injectable()

export class UiLayoutService {

startArrowIsVisible: boolean = true;

openStartArrow() {
this.startArrowIsVisible = true;
console.log('openStartArrow', this.startArrowIsVisible);
}

closeStartArrow() {
this.startArrowIsVisible = false;
console.log('closeStartArrow', this.startArrowIsVisible);
}
...

}

navigation-cart.component.tsstart-arrow.component.ts 都有 UiLayoutService注入(inject)

start-arrow.component.html

<a (click)="uiLayoutService.openStartArrow();">Open</a>
<a (click)="uiLayoutService.closeStartArrow();">Close</a>

<div id="start-arrow" [ngClass]="{active: uiLayoutService.startArrowIsVisible}">
... Some pretty content here ...
</div>

navigation-cart.component.html

<a (click)="uiLayoutService.openStartArrow();">Open</a>
<a (click)="uiLayoutService.closeStartArrow();">Close</a>
... Some other content...

这就是困扰我的事情:

  • 如果我点击OpenClose来自内部的链接 <start-arrow>一切都很好。模板已更新并<div id="start-arrow"> get 按预期关闭或重新打开。控制台显示这些操作运行良好。
  • 如果我点击OpenClose来自内部的链接 <navigation-cart>控制台触发消息,我看到 startArrowIsVisible值正在更新,但 <start-arrow> 中没有发生模板更新。 [ngClass]="{active: uiLayoutService.startArrowIsVisible}只是似乎没有触发模板更新。我想这是因为为了防止不必要地渲染所有应用程序的布局而进行的优化。在这种情况下如何触发布局刷新?

最佳答案

我假设您多次提供 UiLayoutService 服务,并且单击时,该值会在与组件 View 绑定(bind)的实例不同的实例上更新。 Angular DI 为每个提供者创建一个新实例。如果您希望在应用程序之间共享单个实例,只需在根组件(或另一个公共(public)父组件)上共享一次即可

关于javascript - Angular 2 更改检测,ngClass 模型由同级组件更新,但模板未刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com