S
S
Samat2021-07-23 19:25:35
Angular
Samat, 2021-07-23 19:25:35

How to bind correctly in Angular?

Yesterday there was a dispute
And so, there are two options for binding, for example, a class:

1) there is an array of data and the class is taken from there

div [class]="elelent.class"

elements: {
id: number;
class:  string;
}


2) We send the getClass() method to the class bind

div [class]="getClass(id)"

getClass(id: number): string {}


I think that the second option (with the method in the bind) is not acceptable, because I noticed that it is called every time on any scroll or event in the browser, which has a bad effect on the performance of the front

. And I began to look for whether it is possible and recommended at all to bind something in a similar way, I didn’t find anything about this in the documentation, moreover, I found that you can do this in the best-practices section ....
And I don’t understand why it works like that and why you can do it at all, if it has such a detrimental effect on performance.

In VUE, by the way, there are computed properties that just give the desired effect. Re-renders only if something has changed, in general, I would like to achieve this in Angular

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2021-07-25
@Mileon

All computed or just asynchronous things need to be stored in an Observable. There will be a complete analogue of your computed.
For example, there is a variable
src = new BehaviorSubject(1);
From it we calculate the class

myClass = this.src.pipe(map(v => v === 1 ? 'one' : 'two'))

The template will be
div [ngClass]="myClass | async"
When changing src, i.e. src.next(2)
MyClass will be recalculated (once) and the template will be changed (also once, if there are no other reasons for changes and it is worth on-push)
And if it is not requested anywhere, then there will be no recalculation, because it is lazy evaluation, just like computed.
Any data and events are managed this way, and it's a much more flexible system than vue's hidden getters/setters, although sometimes more verbose. And it takes more time to get used to.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question