1. Understanding @Input
The @Input decorator allows data to flow from a parent component to a child component. It establishes a one-way binding, where the parent component can pass data to the child component as an input property. The child component can then utilize this data within its template or logic.
To define an input property, use the @Input decorator followed by the property name in the child component. For example:
@Input() myProperty: string;
In the parent component template, you can bind a value to this property:
parentValue is a property defined in the parent component.
The child component can access the value of
myProperty and use it within its template or logic. Any changes made to the input property in the parent component will automatically reflect in the child component.
2. Understanding @Output
The @Output decorator allows a child component to send data or trigger events to its parent component. It establishes a one-way binding in the opposite direction, from child to parent. This enables communication between components and facilitates interactivity in the application.
To define an output property, use the @Output decorator followed by an EventEmitter object. For example:
@Output() myEvent: EventEmitter<any> = new EventEmitter<any>();
In the child component template or logic, you can trigger the event using the EventEmitter:
The parent component can listen to the output event emitted by the child component using event binding. For example:
In the parent component, define a method
handleEvent() to handle the emitted event and access the data sent by the child component.
3. Two-Way Data Binding using [(ngModel)]
Angular provides a shorthand notation for two-way data binding using [(ngModel)]. It combines the functionality of @Input and @Output into a single directive, simplifying the code and enhancing productivity.
To use [(ngModel)], import the FormsModule in the module and then bind it to a property in the component template:
Any changes made to the input field will automatically update the
property value, and vice versa.
In Angular, the @Input and @Output decorators play a crucial role in component communication. The @Input decorator facilitates passing data from a parent component to a child component, while the @Output decorator allows the child component to send data or trigger events to its parent. Happy Coding!
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency