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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With