Refactoring Angular components from many inputs/outputs to a single config object

前端 未结 5 1259
北海茫月
北海茫月 2021-01-03 19:56

My components often start out by having multiple @Input and @Output properties. As I add properties, it seems cleaner to switch to a single config

5条回答
  •  孤独总比滥情好
    2021-01-03 20:20

    Are there any downsides to having a single config object as an input to a component, instead of having multiple input and outputs?

    Yes, when you want to switch to the onpush change detection strategy, which is often needed in bigger projects to mitigate performance issues caused by too many render-cycles, angular will not detect changes that happened inside your config object.

    Will avoiding @Output and EventEmitter like this cause any issues that might catch up to me later?

    Yes, if you start to move away from @Output and in your template directly operate on the config object itself, then you are causing side-effects in your view, which will be the root of hard-to-find bugs in the future. Your view should never modify the data it get's injected. It should stay "pure" in that sense and only inform the controlling component via events (or other callbacks) that something happened.

    Update: After having a look at the example in your post again, it looks like you did not mean that you want to directly operate on the input model but pass event emitters directly via the config object. Passing callbacks via @input (which is what you are implicitly doing) also has it's drawbacks, such as:

    • your component gets harder to understand and reason about (what are its inputs vs its outputs?)
    • cannot use banana box syntax anymore

提交回复
热议问题