I have a class (interface) in my angular 4 app which has a lot of fields.
Note that the instance of this class/interface is immutable
(i.e. the members will NEVER be changed).
E.g.
public interface IHaveALotOfFields {
field1: string;
//...
field500: string;
}
This interface is provided via a (singleton / application level provided) service which exposes the class as a member. E.g.
@Injectable()
public class MyService {
public translations: ITranslationsProvider;
}
The service is injected into a lot of components (almost all components) and often used in their corresponding template and often also in the ts
-part of the component. E.g.
@Component({
template: `Value: {{service.field500}}`
})
export class MyComponent {
public constructor(public service: MyService) {
}
private doSomething(): string {
return this.service.field1;
}
}
Now my questions:
ChangeDetectionStrategy.OnPush
, but instead of specifying this for each component, can be declared on the class itself or on the member of the service)Please note that I don't want to change the change-detection strategy of all my components to OnPush
.
Will a big class (with a lot of fields) make angular slow because of the change detection?
No. Angular change detection performs two operations that read class properties:
For these operations Angular compiler creates two functions:
These functions read only specific properties from the service. For your example
Value: {{service.field500}}
the updateRenderer
function will look something along the lines:
function(_ck,_v) {
var _co = _v.component;
var currVal_0 = _co.service.field500;
_ck(_v,1,0,currVal_0);
These functions are called on each digest loop. But as you can see only the relevant property will be read from the service. So it doesn't matter how many properties there are on the service.
Is there any way to mark a class as "Ignore me on change detection"?
I assume you're asking about one-time binding like we had in AngularJS. Maybe it will be added in Angular as well. I'll be monitoring that and update the answer if something comes up. But as you probably know you can disable/enable change detection for the component using cd.detach/cd.attach
. You can listen for some signal from the service and run cd manually when neeed.
Here is the list of articles you could read to understand the mechanics of change detection better:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With