angular - 当从父级触发更改时,Angular 子组件视图不会更新
问题描述
我是 Angular 的新手,我正在努力解决一些基本问题。我有一个模块试图显示覆盖(第二个模块)。覆盖有一个函数 show() 当从父调用时不会更新子 html。如果它是从孩子的 onInit() 调用的 - 它工作正常。
我想我错过了一些简单的东西,但找不到它。你能帮我弄清楚发生了什么事吗?
这是代码:父视图:
export class SalesComponent {
constructor(private groupsSelectorOverlayComponent: GroupsSelectorOverlayComponent) {
}
onBtnGroupsClick() {
// this is the problematic call. It changes the child's properties, but the child view is not updated
this.groupsSelectorOverlayComponent.show(-1);
}
}
子视图:
@Component({
...
})
export class GroupsSelectorOverlayComponent implements OnInit {
public isOpen: boolean = false;
public groupsResponseData: GroupsResponseData = null;
constructor(private stocksService: StocksService) {
this.isOpen = false;
}
ngOnInit(): void {
// if we call show() from here, the view is updated
}
show(parentGroupId: number) {
this.stocksService.getGroups(parentGroupId).subscribe((response) => {
// we enter here, the values are updated, but when this is called from the parent, the view is not updated
this.groupsResponseData = response;
this.isOpen = true;
});
}
}
子模板:
<ul *ngIf="groupsResponseData != null" class="groupPages">
<li *ngFor="let page of groupsResponseData.groups_info" class="groupPage">
<div class="title">{{ page.page_name }}</div>
</li>
</ul>
在 app.module.ts 我有这个:
providers: [
GroupsSelectorOverlayComponent
],
解决方案
在您的父母中,创建一个
@ViewChild(GroupsSelectorOverlayComponent)
child:GroupsSelectorOverlayComponent
然后像这样调用它:
this.child.show=(-1);
但请记住,在所有视图都初始化之前,您不能调用它。否则 this.child 将是未定义的。
不要忘记
ChangeDetectorRef.DetectChanges();
推荐阅读
- amazon-web-services - 无法创建 CloudFormation 堆栈
- ios - 在运行主要目标 Xcode 之前构建所有框架
- ansible - 列出将被“yum autoremove”删除的包?
- html - CSS 错误:为什么页眉水平对齐和页脚不均匀对齐?
- php - 如何使用从数据库行请求的布尔值在 laravel-php 中制作触发器?
- javascript - 用 Node.js 写出巨大的 json (4 Gb)
- magento2 - 1 个异常:异常 #0 (Magento\Framework\Exception\LocalizedException):方法无效 Magento\Catalog\Block\Navigation::canShowBlock
- java - 为具有 permitAll 权限的端点获取 401
- java - 使用 JPA/Hibernate 过滤 DataSet 中的行
- c++ - 需要二进制补码的 C++20 的分支