Search code examples
angulardata-bindingangular-changedetection

Angular component doesn't update after API call


I have a dropdown component that takes a model as [input].

on the parent i have:

    public ngOnInit(): void {

        this.initializeDropdown();       
    }

private initializeDropdown(): void {

    this.viewModel.dropdownItems = {
        defaultItem: {
            display: 
            value: undefined
        },
        items: []
    };

    const promise = this.someService.get("SOMEURL");

    promise.then(res => {
        if (Array.isArray(res)) {

            res.map((item) => {

                this.viewModel.dropdownItems.items.push(
                    {
                        display: item.display,
                        value: item.value
                    });
                }
            );
        }
    });
}

The problem is that does not update the child component. So the dropdown does not update. I can see that the viewModel get initialized.

I've binded it with one way [ this.viewModel.dropdownItems ]

I am using this dropdown component elsewhere too so i know that it works. (Dunno about the api call though don't know if i do that else where)


Solution

  • If you are using changeDetection: ChangeDetectionStrategy.OnPush, Keep ChangeDetectorRef and call markForCheck as below.

     constructor(private changeDetectorRef: ChangeDetectorRef) {}
    
     const promise = this.someService.get("SOMEURL");
        promise.then(res => {
            if (Array.isArray(res)) {
    
                res.map((item) => {
    
                    this.viewModel.dropdownItems.items.push(
                        {
                            display: item.display,
                            value: item.value
                        });
                    });
                this.changeDetectorRef.markForCheck();
            }
        });