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?
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.
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: