Angluar2 Observable UI - Update Children in Object Array force Change?

限于喜欢 提交于 2019-12-12 03:28:53

问题


Let's say I have a simple array object like so:

validationMessages = {
    'name': [{
        'type': 'required',
        'message': 'Name is required.',
        'enabled': 1
    },
    {
        'type': 'maxlength',
        'message': 'Name cannot be more than 50 characters long.',
        'enabled': 0
        }],
    'description': [
        {
            'type': 'required',
            'message': 'Description is required.',
            'enabled': 0
        },
    ]
};

I'm then displaying on load in my UI like so:

        <div *ngFor="let err of validationMessages.name">

            <div *ngIf="err.enabled == 1"  class="alert alert-danger">


                {{err.message}}
            </div>
        </div>

Working fine.

However what I'd like to do is be able to update validationMessages.name array to update a given object to mark enabled 1 or 0. I'd want this then to update/re-run my UI.

I'm sure this can be done using observables, but what am I missing to do this?


回答1:


If you don't modify the object within some event (button click, value change) or async call, you must tell Angular that you want the component to be refreshed.

controller(private changeDetectorRef: ChangeDetectorRef) {}
changeValidationMessages(): void {
   this.validationMessages...enabled = 0;
   this.changeDetectorRef.markForCheck();
}

There is no need to use Observables for that, but if you did, you would probably use the async pipe to display the messages. The pipe calls the ChangeDetectorRef itself.

The other way of making sure model changes get reflected in UI is using immutable objects (creating a new object copy whenever you want to modify an existing one), but it also adds some complexity.

Angular's change detection system is a topic worth knowing in more detail. You can check the following articles:

  • https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
  • https://blog.thoughtram.io/angular/2017/02/27/three-things-you-didnt-know-about-the-async-pipe.html


来源:https://stackoverflow.com/questions/43397599/angluar2-observable-ui-update-children-in-object-array-force-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!