Angular 2更改检测,ngClass模型由同级组件更新,但模板确实更新了'不要精神抖擞

Angular 2 change detection, ngClass model gets updated by sibling component but the template does't get refreshed

本文关键字:更新 精神抖擞 ngClass 检测 模型 Angular 组件      更新时间:2023-09-26

我有一个类似这样的设置:

main.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);
    }
    ...
}

导航cart.component.ts启动箭头.component.ts都具有UiLayoutService注入

启动箭头.组件.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>

导航cart.component.html

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

以下是困扰我的问题:

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

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