5

I'm wondering which of the following is better

<my-component [data]="settings"></my-component>

or

<my-component 
    [bar]="settings.foo.bar"
    [baz]=settings.baz"></my-component>

And the settings object would then look like this

this.settings = {
    foo: { bar: 10 }
    baz: 2
};

The first form is compact, but less explicit about what my-component needs. I can image that there are situation in which it could be better to pass whole objects to a component (if there are too many properties for example). And what about performance. I can image that change detection is harder and less performant if you pass around whole objects. Any help/tips regarding this subject would be appreciated!

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • Possible duplicate of [Refactoring Angular components from many inputs/outputs to a single config object](https://stackoverflow.com/questions/47743281/refactoring-angular-components-from-many-inputs-outputs-to-a-single-config-objec) – molikh Nov 28 '18 at 14:12

3 Answers3

3

I think specifying individual values is a better approach. As you wrote, it's more explicit about what you need, and you can specify the values from other sources (not just the settings object). This way, change detection is easy and your component can be optimized by using

@Component({  
  changeDetection: ChangeDetectionStrategy.OnPush
})

Using the OnPush strategy, Angular will skip the change detection for the component's subtree if none of its input values changed.

For more info see

Ján Halaša
  • 8,167
  • 1
  • 36
  • 36
2

As far as my experience is concerned, the priority in front end software development today should be on code readability. As in terms of performances the difference is neglectable, I would opt for the first option, where you clearly pass a single settings object. When reading the .html page, there is no interest in digging in further here; the 'reader' can see the structure of your variable somewhere else in the script.

Jacopo Lanzoni
  • 1,264
  • 2
  • 11
  • 25
1

Better option is first. HTML code is more concise, when someone will need to find out what is settings, then no problem jump to ts file. Typescript types are a good way to identify objects, so you don't need to pass properties separately.

Emerceen
  • 2,735
  • 3
  • 17
  • 22