Angular: best way to pass data to component (object versus many arguments)

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 then the settings object will look like this:

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

      

The first form is compact, but less clear about what it needs my-component

. I can imagine there is a situation where it is best to pass whole objects to a component (if there are too many properties, for example). What about performance. I can imagine detecting changes is more difficult and less effective if you walk around whole objects. Any help / advice on this matter would be appreciated!

+3


source to share


3 answers


I think defining individual values ​​is the best approach. As you wrote, it describes in more detail what you need, and you can specify values ​​from other sources (not just for the settings object). This way, change detection is easy and your component can be optimized with

@Component({  
  changeDetection: ChangeDetectionStrategy.OnPush
})

      

Using strategy OnPush

, Angular will skip change detection for a component subtree if none of its input values ​​have changed.



For more details see

+3


source


In my experience, the priority in end-user software development today should be on code readability. As with stats, the difference is not taken into account, I would choose the first option, where you clearly pass one object settings

. When reading a .html page, there is no interest in digging; the "reader" can see the structure of your variable somewhere else in the script.



+1


source


Better to choose an option. The HTML code is more concise, when someone needs to know what the settings are, then there is no problem going to the ts file. Typescript types are a good way to identify objects, so you don't need to pass properties separately.

+1


source







All Articles