DEV Community

GaurangDhorda
GaurangDhorda

Posted on

Component property Binding in Angular and Vue3

How to detect change of child component property and assign changed value to local scope variable in both angular and vue3.

You can support me

Alt Text

Both angular and vue3 provides better way to communicate between parent and child component using property binding. It is common practice to follow that not manipulate child property object direcetly, rather we detect changes of child property and assign changed data to local component variable, and after that manipulate data inside component using local component variable.

In Angular,
To declare property binding inside child component, Angular provides @Input() decorator. With @Input() decorator we can access property value from child component and parent component needs to pass binded data back to child component using [] property binding data.

// inside parent html.
<child [childProp] = "data" />

// inside child component.
@Input() childProp: unknown; 
Enter fullscreen mode Exit fullscreen mode

In Vue3,
To declare property binding inside child component, Vue3 provides props: { } , inside props object declare all property variable.
and inside parent component pass property binding using :props syntax.

// inside parent template
<Child :childProp = "data" />

//inside child component
props:{
     childProp: Array
}
Enter fullscreen mode Exit fullscreen mode

Now we see how can we assign property value to local variable in both angular and vue3

For Angular, we are using @Input() setter function. this setter function is calling whenever new property value change occurs.

export class ChildComponent implements OnInit {
  tasks = [];
  @Input("tasks") set onTaskChange(taskData) {
    this.tasks = taskData;
  }
  constructor() {}

  ngOnInit() {}
}
Enter fullscreen mode Exit fullscreen mode

Above, onTaskChange setter function is called when tasks props changes and property data is assigned to local tasks class variable.

For Vue3, it is very easy in vue3 using composition api. we are using toRefs from vue3 composition api setup() function.

<script>
    import { toRefs } from 'vue';
    export default{
    name: 'Child',
    props:{
      tasks:{
        type: Array,
        default : [{'id': 0, 'taskName': 'Default Task'}]
      }
    },
    setup(props){
      const localTasks = toRefs(props).tasks;
      return {
        localTasks
      }
    }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Above, setup function is called by vue with local props object. we are creating copy of tasks props using toRefs and assign value to localTasks variable, and we are only returning localTasks from setup(). anything return from setup() is accessible from template of component. now localTasks is reactive variable and whenever prop changes fire our localTasks gets copy of props and template gets new value.

Angular Demo

Vue3 Demo

You can support me

Alt Text

Top comments (0)