read

How can an outer component pass values into an inner component in Angular 2? First lets review how this was handled with directives in Angular 1.

AngularJS

In AngularJS, one way to handle this is using attributes on a directive.

    <some-directive some-attr="{{someValue}}" 
        some-exp="someExpression">

There are then grabbed inside the directive using a somewhat complicated syntax.

    app.directive('someDirective', someDirective);

    function someDirective() {
        return {
            scope: {
                'someAttr': '@', // string value
                'someExp': '='   // two-way binding
            }
        };
    }

First you must know that values can be bound to an expression and use @, and that two-way bound expressions don't take expression and use =. This is just scratching the surface of the complexity of AngularJS directives which has resulted in a lot of developer frustration (as well as thousands of Stack Overflow questions).

Angular 2

In Angular 2, passing data to child components is much easier. Let's have a look.

    <some-component [some-attr]="42" 
        [some-exp]="someExpression">

Attributes are evaluated on the right side and wrapped in square brackets [].

Inside the inner component, these are treated as properties. Keep in mind that snake-cased attributes are still converted to camelCase.

    @Component({
      selector: 'some-component',
      properties: [
          'someAttr', 
          'exp: someExp' // optional alias
      ]
    })

In this case, I've used an alias exp for someExp. Using an alias is optional.

These values will be passed into the view directly.

    @View({
      template: `
        <p>Attribute Value: {{someAttr}}</p>
        <!-- result: 42 (actual value) -->
        <p>Expression: {{exp}}</p>
        <!-- result: 'value of expression' -->`
    })

Values are passed in when the component is initiated and bound to the context of the class. Keep in mind, properties are not passed in when the class is constructed.

    class SomeComponent {
      constructor() {
        console.log(this.someAttr); // undefined
        console.log(this.exp); // undefined
       }
    }

Instead, properties can be handled on the onInit() method, which runs when the component is instantiated in the DOM.

    class SomeComponent {
      onInit() {
         console.log(this.someAttr); // 42
         console.log(this.exp); // 'value of expression'
      }
    }

onInit() is one of several lifecycle events built into Angular 2 components & directives. More on those later.

Example


Conclusion

Angular 2 has a cleaner and more comfortable syntax for passing properties into child components.



Angular 2 Series
Event Emitters | Properties | Pipes | Meteor

Blog Logo

Shawn McKay

Published

Image

ShMcK

JavaScript Web Dev

Back Home