Passing Data into a Component

There are two ways to pass data into a component, with 'property binding' and 'event binding'. In Angular, data and event change detection happens top-down from parent to children. However for Angular events we can use the DOM event mental model where events flow bottom-up from child to parent. So, Angular events can be treated like regular HTML DOM based events when it comes to cancellable event propagation.

The @Input() decorator defines a set of parameters that can be passed down from the component's parent. For example, we can modify the HelloComponent component so that name can be provided by the parent.

  1. import { Component, Input } from '@angular/core';
  2. @Component({
  3. selector: 'rio-hello',
  4. template: '<p>Hello, {{name}}!</p>',
  5. })
  6. export class HelloComponent {
  7. @Input() name: string;
  8. }

The point of making components is not only encapsulation, but also reusability. Inputs allow us to configure a particular instance of a component.

We can now use our component like so:

  1. <!-- To bind to a raw string -->
  2. <rio-hello name="World"></rio-hello>
  3. <!-- To bind to a variable in the parent scope -->
  4. <rio-hello [name]="helloName"></rio-hello>

View Example

Unlike Angular 1.x, this is one-way binding.

原文: https://angular-2-training-book.rangle.io/handout/components/app_structure/passing_data_into_components.html