首页 > 解决方案 > 当从父级触发更改时,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
],

标签: angular

解决方案


在您的父母中,创建一个

@ViewChild(GroupsSelectorOverlayComponent)  
   child:GroupsSelectorOverlayComponent 

然后像这样调用它:

this.child.show=(-1);

但请记住,在所有视图都初始化之前,您不能调用它。否则 this.child 将是未定义的。

不要忘记

ChangeDetectorRef.DetectChanges();

推荐阅读