Learn About Inputs and Outputs in Angular | Sample Code Included

In Angular, an input is a way to pass data from a parent component to a child component. The child component can use the data provided by the parent component in its own template or logic.

On the other hand, an output is a way for a child component to communicate with its parent component. The child component can emit events, such as button clicks or form submissions, which the parent component can listen to and respond accordingly.

Here's a sample code that demonstrates how to use inputs and outputs in Angular:

typescript
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
    <div>
      <p>{{message}}</p>
      <button (click)="onButtonClick()">Click me!</button>
    </div>
  `
})
export class ChildComponent {
  @Input() message: string;
  @Output() buttonClick = new EventEmitter();

  onButtonClick() {
    this.buttonClick.emit();
  }
}

@Component({
  selector: 'parent-component',
  template: `
    <div>
      <child-component [message]="parentMessage" (buttonClick)="onChildButtonClick()"></child-component>
    </div>
  `
})
export class ParentComponent {
  parentMessage = 'Hello from parent!';

  onChildButtonClick() {
    console.log('Child button clicked!');
  }
}

In this example, we have a `ChildComponent` that takes in a message through an input property called `message`, and emits a button click event through an output property called `buttonClick`.

The `ParentComponent` uses the `ChildComponent` in its template and passes in a message through the message input property. It also listens to the buttonClick output event and calls a method called `onChildButtonClick()` when the button is clicked.

When the application runs, the `ChildComponent` will display the message passed in from the parent, and when the button is clicked, it will emit the `buttonClick` event which will trigger the `onChildButtonClick()` method in the parent component.

Example video of how it works: