Angular’s @Input() decorator is great. It serves as the go to way of passing data from a parent component to it’s child components. Then what is @Input() setter? How is it different from @Input()? When to use it?

Let’s explore.

@Input() decorator indicates that the marked field is an input property that can receive data from a parent component. If this field is bound to the component’s template, then Angular automatically takes care of refreshing it anytime the value changes in parent component.

But there are times, when we would like to use the input data to drive dependent logic in the child component. The result of this logic may or may not be referenced in the child component’s template. But we must trigger the evaluation anyway whenever the input data to keep our application state valid across components.

If the child component is destroyed and re-instantiated during this input data change, then we could handle the scenario in ngOnInit() method. However, it’s not always the case. The child component may stay loaded on the DOM for the entire life cycle of the application. In that case, how do we force an evaluation of the dependent logic?

A widely used approach is to implement ngOnChanges() life cycle hook method. But if not done properly this approach could lead to problems. For example, if the child component is receiving multiple @Input() fields then ngOnChanges() fires when any of the incoming data changes. This could lead to potential problems if the logic is compute intensive or makes network calls. So we must write conditional statements inside ngOnChanges() that ensures we trigger evaluation for changes only to the input property that we want.

#web-development #javascript #angular

Understanding @Input vs. @Input setter in Angular
15.90 GEEK