gpt4 book ai didi

angular - 如何在内部状态发生变化时触发 Angular Controller 方法?

转载 作者:行者123 更新时间:2023-12-05 06:57:42 28 4
gpt4 key购买 nike

当内部数据模型发生变化时,使我的 Angular 组件调用绑定(bind)方法(在此示例中为 isItemExpended)的最佳方法是什么?

typescript

@Component({
...
})
export class ItemsComponent implements OnInit {
...

private expandedItems: Item[] = [];

public isItemExpanded(item: Item): boolean {
return this.expandedItems.indexOf(item) > -1;
}

...
}

HTML

<ng-container *ngFor="let item of items">
<div *ngIf="isItemExpanded(item)">
...
</div>
</ng-container>

注意:在我的解决方案中,isItemExpanded 的实现有点复杂,这就是没有直接在 HTML 中设置条件的原因。

最佳答案

@Component({
...
})
export class ItemsComponent implements OnInit {
...
constructor(private cd: ChangeDetectorRef){}

private expandedItems: Item[] = [];

public isItemExpanded(item: Item): boolean {
return this.expandedItems.indexOf(item) > -1;
}
private listenModel() {
model.changed$.subscribe() {this.cd.markForCheck()}
}
...
}

关于angular - 如何在内部状态发生变化时触发 Angular Controller 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64863654/

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