Angular @Input @Output and EventEmitter

Learn how to utilise @input, @output, and EventEmitter in Angular in this tutorial. These decorators are used to transfer data between parent and child components and vice versa. The component’s input property is defined by @Input and may be changed by the parent component. The output property (event), which we raise in the child component using the EventEmitter, is defined by the @output tag. The parent is aware of these happenings.

@Input

The property is identified as an input property by the input decorator. It can, thus, receive information from the parent component. The parent component ties itself to a component property via property binding. Angular updates the value in the child component whenever the value in the parent component changes.

Example

@Component({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
  @Input() customer:Customer;
}

Our input decorator is now on the client’s property. The component anticipates receiving its value from the parent component.

The customer object is supplied by the parent component using the property binding syntax. We enclose the client’s property in square brackets. Give it the template expression (selectedCustomer), which is a parent component property.

<app-customer-detail [customer]="selectedCustomer"></app-customer-detail>

@Output

As the output property, output embellishes the property. It is started as an EventEmitter. The child component initiates the event and provides the data as an argument. The parent component reads the data while utilising event binding to listen to events.

Example

//Declare the property
@Output() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>();
 
//Raise the event to send the data back to parent
update() {
  this.customerChange.emit(this.customer);
}

Output property of type EventEmitter, customerChange, is used.

Using the event binding syntax, we subscribe to the event in the parent component. To assign a template statement to an event, use the () symbol around the event name (customerChange). The information is sent to it in the $event parameter.

<app-customer-detail [customer]="selectedCustomer" (customerChange)="update($event)"></app-customer-detail>

Keep in mind that the parameter name must be $event.

EventEmitter

The event must be raised by EventEmitter. Typically, the @output property is of the EventEmitter type. The emit() function of the child component will be used to emit an event along with the data.

//Define  output property
@Output() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>(); 
 
//Raise the event using the emit method.
update() {
  this.customerChange.emit(this.customer);
}

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories