Code Whisperer
Code Whisperer

Reputation: 23652

What is the reason for the "inputs" property of a component in an Angular 2 app?

From the docs,

'The input declaration ensures that consumers of our directive can only bind to the properties of our public API ... nothing else.'

https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#why-input

This is not super clear. I'm not really sure why we need to define this at all. Could someone explain?

Upvotes: 1

Views: 79

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657356

@Input() someInput; (or @Component({inputs: ['someInput']})) creates a property on your custom element you can bind to like

<my-component [someInput]="someField"></my-component>

Without the @Input() the binding wouldn't be allowed and you'd get an error message when loading the Angular application.

There are also other reasons for this declarative approach:

  • It should allow tools to get meta information about your components
    • for syntax-checks
    • autocompletion
  • Angular2 uses this meta information to generate code that hooks up the binding
    • for example ngOnChanges() is called when a binding to an input changes.

Upvotes: 3

Related Questions