gpt4 book ai didi

angular - 谁拥有 Angular Dart 中的 TemplateRef 刷新周期?

转载 作者:行者123 更新时间:2023-12-03 03:26:21 24 4
gpt4 key购买 nike

与 ngTemplateOutlet 一起使用时,我遇到了 TemplateRef 刷新周期的问题。

考虑 HTML:

           <card [value]="item" full>

<template #buttons let-obj="obj"> <!-- THE TEMPLATE -->
<button (click)="myBoolean = false"
*ngIf="myBoolean"> <!-- THIS IF -->
SET FALSE
</button>

<button (click)="myBoolean = true"
*ngIf="!myBoolean"> <!-- THIS IF -->
SET TRUE
</button>
</template>

</card>

<button (click)="myBoolean = !myBoolean">TOGGLE</button>

所以页面组件有一张卡片。
该卡具有以下属性:
  @ContentChild('buttons')
TemplateRef buttons;

此代码使用 TemplateRef 按钮:
<template [ngTemplateOutlet]="buttons"
[ngTemplateOutletContext]="{ 'obj': value }"></template>

它运行良好,按钮显示基于页面组件的 myBoolean 变量。此外,当您单击 <template> 内的按钮时循环有效,它们根据 myBoolean 变量而变化。

问题是当 myBoolean 变量被 <template> 之外的东西改变时.在上面的 HTML 示例中,当我单击 TOGGLE 按钮时,myBoolean 变量会发生变化,但是 <template>不会相应地刷新。

那么,谁拥有 TemplateRef 的刷新呢?
我该怎么做才能使其正确刷新?

最佳答案

TemplateRef 所在的 View 被实例化拥有所有权。因为您的组件使用 ChangeDetectionStrategy.OnPush ,他们的观点只会在任何时候更新

  • 绑定(bind)在
    组件的 View 被触发,
  • 输入的值(例如 (event)=handleEvent )更改,或
  • 组件已注入(inject) <card [input]="value">并调用 ChangeDetectorRef .

  • 请注意,所有这三个条件都会导致 View 被标记为检查;前两个是隐式的,最后一个是显式的。

    在您的示例中,您正在投影 changeDetector.markForCheck()进入您的 <template>组件的 View 。大概是你的 <card>组件然后呈现 <card>通过 <template> 在自己的 View 中.所以为了渲染 NgTemplateOutlet将在 <template> 时更新更改, myBoolean必须标记组件以供检查。

    单击 <card> 中的按钮时 View 正确更新的原因是由于上述原因(1)。事件处理程序标记要检查的 View ( <template>)。

    同样的原因是当您单击父 View 中的 TOGGLE 按钮时它不起作用的原因:这只标记要检查的父 View 。因此,当父 View 因标记为检查而检测到更改时, <card> View 被跳过,因为 <card> 的三个条件都不满足。看法。

    所以为了得到渲染的 <card>单击 TOGGLE 按钮时更新,您需要处理程序以某种方式调用 <template>markForCheck() ChangeDetectorRef 的 View 被渲染。

    好消息是这是可能的,但不幸的是它不是很干净。有很多方法可以实现这一点,但这里有一个想法:

    <template> 添加方法抽象使用 <card> 的细节:
    @Component(...)
    class CardComponent {
    CardComponent(this._changeDetector);

    final ChangeDetectorRef _changeDetector;

    void updateButtons() {
    _changeDetector.markForCheck();
    }
    }

    查询 ChangeDetectorRef在您的页面组件中,并在按下切换时调用更新方法:
    @Component(...)
    class PageComponent {
    @ViewChild(CardComponent)
    CardComponent card;

    void toggle() {
    myBoolean = !myBoolean;
    card.updateButtons();
    }
    }
    <button (click)="toggle">TOGGLE</button>

    希望这有帮助,干杯!

    关于angular - 谁拥有 Angular Dart 中的 TemplateRef 刷新周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332923/

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