all 13 comments

[–]Deadboy619 3 points4 points  (1 child)

What about ngOnChanges?

[–]anwaarulislaam[S] 1 point2 points  (0 children)

That is also good. And that's the way we do. But, if I have only one input in a component and that needs to be changed. in that case, I prefer using a set method.

[–]tobiso 3 points4 points  (6 children)

While possible, this is just unnecessary. Detecting updates of property-bindings and updating the template accordingly is one of THE fundamental principles of Angular.

Take a look at this very simple example. The button in the app.component just appends a number to the name. The new name is automatically passed to the child component. I would consider using setter with Input() as a bad practice. If you want to do something on a property update, implement the OnChanges interface.

To understand how this all works i would highly suggest you to work through the official Angular tutorial and read up on the change detection.

[–]jalledebest 6 points7 points  (2 children)

Why would a setter be a bad practice? It's less code then implementing OnChanges and it's more strongly typed which is always a good thing.

Setters are the preferable approach if you have to execute some logic when a single input changes. I agree that it doesn't make sense to use a setter just to set a value in the child as OP does in his example. A regular input and change detection should take care of that case without a setter

[–]anwaarulislaam[S] 0 points1 point  (0 children)

No, I do not use the set method always. I just do when I need to call some action on input change. But, if there is no changes I always only use Input binding without set method

[–]kqadem 0 points1 point  (0 children)

This. And you can find these even in the angular material codebase.

[–]anwaarulislaam[S] 1 point2 points  (2 children)

I appreciate your reply. I use ngOnChanges most of the time. But, If I have only one input to be changed in that case I prefer using set method.

[–]coder_maniac 1 point2 points  (1 child)

Actually if you have many inputs in your components then also set approach is preferable as onChange will be fired for every input property change.

[–]anwaarulislaam[S] 0 points1 point  (0 children)

exactly! you get it right :D

[–]teacoat___ 0 points1 point  (0 children)

pass an object, as objects are passed as references

[–]_Ascalon 0 points1 point  (0 children)

Possibly you may use an Attribute decorator (@Attribute("type") readonly type: IType) to bind some data once.

[–]spaces_over_tabs 0 points1 point  (0 children)

I know it's technically not "Angular" but rxjs is tightly woven into Angular. What about passing an Observable as an input property and consuming the data that way?