Angluar2可观察的UI-更新对象数组中的子级强制更改? [英] Angluar2 Observable UI - Update Children in Object Array force Change?
问题描述
假设我有一个像这样的简单数组对象:
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
},
]
};
然后,我将在加载时显示在UI中,如下所示:
<div *ngFor="let err of validationMessages.name">
<div *ngIf="err.enabled == 1" class="alert alert-danger">
{{err.message}}
</div>
</div>
工作正常.
但是我想做的是能够更新validationMessages.name
数组以更新给定对象以标记enabled
1或0.我希望它随后可以更新/重新运行我的UI. /p>
我确定可以使用可观察对象来完成此操作,但是我缺少这样做吗?
如果您未在某个事件(按钮单击,值更改)或异步调用中修改对象,则必须告知Angular您希望该组件为刷新.
controller(private changeDetectorRef: ChangeDetectorRef) {}
changeValidationMessages(): void {
this.validationMessages...enabled = 0;
this.changeDetectorRef.markForCheck();
}
不需要使用Observables,但是如果这样做了,则可能会使用async
管道来显示消息.管道调用ChangeDetectorRef
本身.
确保模型更改反映在UI中的另一种方法是使用不可变的对象(只要您想修改现有对象,就创建一个新的对象副本),但这也会增加一些复杂性.
Angular的变更检测系统是一个值得更详细了解的主题.您可以查看以下文章:
- https://blog .thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
-
Working fine.
However what I'd like to do is be able to update
validationMessages.name
array to update a given object to markenabled
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?
解决方案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 theChangeDetectorRef
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
这篇关于Angluar2可观察的UI-更新对象数组中的子级强制更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!