Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @Input and inputs in Angular2 Components?

Tags:

angular

I am pondering this issue and can't find any explanation.

When passing parameters to a Component in Angular2

Given

<my-component [attr]="someModelVariable"></my-component>

There seems to be two ways of accepting the attr bound value:

@Component{(
    selector: "my-component",
    inputs: ["attr"]
)}
export class MyComponent {
}

Or you do this:

@Component{(
    selector: "my-component"
)}
export class MyComponent {
    @Input()
    public attr: any;
}

And I have actually seen code that uses both at the same time, Can someone explain what the differences between them are?

/Rickard

like image 504
Rickard Staaf Avatar asked Nov 11 '15 10:11

Rickard Staaf


1 Answers

It is true that @Input allows easy definition of type, scope and default values, but the availability of getters and setters means that the functionality is effectively the same with both techniques.

I'm not about to suggest using inputs over @Input, and I agree with the other posters that it is best to stick to the current style guide, but I did find it a useful exercise to compare the two approaches when I came across them myself.

Below is a fuller comparison also using getters and setters to hopefully demonstrate the differences in layout and similarities in behaviour.

Using inputs

@Component({
    selector: 'my-component',
    template: '<h2>Value = {{ attr }}</h2>',
    inputs: ['attr']
})
export class MyComponent {

  public _attr: string;

  set attr(value) : void {
    console.log(`setter: ${value}`);
    this._attr = value;
  }

  get attr() : string {
    console.log(`getter: ${this._attr}`);
    return this._attr;
  }
}

And using @Input:

@Component({
    selector: 'my-component',
    template: '<h2>Value = {{ attr }}</h2>'
})
export class MyComponent {

  public _attr: string;

  @Input()
  set attr(value: string) : void {
    console.log(`setter: ${value}`);
    this._attr = value;
  }
  get attr() : string {
    console.log(`getter: ${this._attr}`);
    return this._attr;
  }
}
like image 54
Jason Avatar answered Oct 16 '22 15:10

Jason