Outline

Input/Output Bindings

As we've learned, Angular provides one-way data binding, enabling us to input data into a directive, as well as output data out of a directive. Let's dive into input and output data bindings.

Input Data Binding

Input data binding is accomplished using a squre-bracket ( [] ) syntax in your templates on the component directive.

For example, we have a PersonDetailsComponent directive whose selector value is app-person-details:

@Component({
  selector: 'app-person-details'
})
export class PersonDetailsComponent {
  @Input() person: Person;
}

We can then implement (or use) this component directive in template as follows:

<app-person-details [person]="p"></app-person-details>

In the example above the input data binding in the template is being specified for the person input, and it is being set to the value of the p property in the parent component directive. The parent PersonListComponent directive might look like:

@Component({
  selector: 'app-person-list',
    template: `
      <app-person-details [person]="p"></app-person-details>
    `
})
export class PersonListComponent {
  p = new Person();
}

Output Data Binding

Output data binding is also accomplished using parenthesis syntax in your templates on the component directive.

Using our previous example of the PersonDetailsComponent directive we will also specify a selected output. We'll receive the value of this event using a special $event syntax in our templates:

<app-person-details [person]="p" (selected)="onSelected($event)"></app-person-details>

The value of $event is whatever value the output emits.

Now, let's update our PersonListComponent and declare the onSelected() method:

@Component({
  selector: 'app-person-list',
    template: `
      <app-person-details [person]="p"></app-person-details>
    `
})
export class PersonListComponent {
  p = new Person();

    onSelected(person: Person) {
      // do something with the person that has been selected
    }
}

The onSelected method is invoked when the selected output event emitter emits a value to the parent component directive.

 

I finished! On to the next chapter