interview community logo

0
0
Data binding types in Angular
1 answer

What are the data binding types available in Angular?

Angular Robert Isaac asked 1 year ago

1 - Robert Isaac commented 4 months ago

0

there are 3 types of data binding in Angular

  1. from parent to children using @Input()

this is the most used data binding, it helps to pass data from the parent to its children using pre-defined @Input in the child

it's defined in the child component ts like that @Input() inputName?: string or being required like that @Input({required: true}) inputName!: string

and it can be used in the parent like that <app-child [inputName]="value"/> where value is a component variable defined in the component ts

  1. from children to parent using @Output()

it should be of type EventEmitter it allows the child component no notify the parent about a change that happen in it

it's defined in the child component ts like that @Output() notifyParent = new EventEmitter<number)(); and can notify the parent then using this.notifyParent.emit(1)

it's used in the parent like t hat <app-child (notifyParent)="takeAction($event)"/> where $event is the value passed in the emit in the child and takeAction is a method defined in the parent component

  1. two way data binding using @Input with @Output() together, where the @Output name is the @input name added change word to it

it's defined in the child component ts like that

  @Input({required: true})  size!: number;
  @Output() sizeChange = new EventEmitter<number>();

it can be used like that in the parent <app-child [(size)]="value"/>, now whenever size is emitted in the child it will be automatically updated in the parent, and whenever the value changed in the parent it will be automatically in the child, child should never change the value inside its component without emitting the value

Robert Isaac answered 1 year ago loading comments...