从父级触发更改时,Angular子级组件视图未更新

时间:2020-10-15 13:20:36

标签: 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
],

1 个答案:

答案 0 :(得分:1)

在您的父母中,创建一个

@ViewChild(GroupsSelectorOverlayComponent)  
   child:GroupsSelectorOverlayComponent 

然后这样称呼它:

this.child.show=(-1);

但是请记住,只有在所有视图初始化之后才能调用它。否则,this.child将是不确定的。

别忘了

ChangeDetectorRef.DetectChanges();