Share what worked for me:
Adding input to an Angular 4 application
Assuming we have 2 components:
parent-componentchild-component
We wanted to pass some value from parent-component to child-component , i.e. @Input from parent-component.html to child-component.ts . The following is an example explaining the implementation:
parent-component.html looks like this:
<child-component [someInputValue]="someInputValue"></child-component>
parent-component.ts looks like this:
class ParentComponent { someInputValue = 'Some Input Value'; }
child-component.html looks like this:
<p>Some Input Value {{someInputValue}}</p>
child-component.ts looks like this:
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child-component', templateUrl: './child-component.html' }) export class ChildComponent implements OnInit { @Input() someInputValue: String = "Some default value"; @Input() set setSomeInputValue(val) { this.someInputValue += " modified"; } constructor() { console.log('someInputValue in constructor ************** ', this.someInputValue);
Note that the @Input value @Input available inside ngOnInit() and not inside constructor() .
Object Reference Behavior in Angular 2/4
In Javascript, objects are stored as links .
This exact behavior can be replayed using Angular 2/4. The following is an example explaining the implementation:
parent-component.ts looks like this:
class ParentComponent { someInputValue = {input: 'Some Input Value'}; }
parent-component.html looks like this:
{{someInputValue.input}}
child-component.html looks like this:
Some Input Value {{someInputValue}}
change inputchild-component.ts looks like this:
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child-component', templateUrl: './child-component.html' }) export class ChildComponent implements OnInit { @Input() someInputValue = {input:"Some default value"}; @Input() set setSomeInputValue(val) { this.someInputValue.input += " set from setter"; } constructor() { console.log('someInputValue in constructor ************** ', this.someInputValue);
The changeInput() function will change the value of someInputValue inside ChildComponent and ParentComponent due to their reference. Since someInputValue refers to the ParentComponent someInputValue object - a change in the ChildComponent someInputValue object changes the value of the ParentComponent someInputValue object . IT IS NOT RIGHT. Links will never be changed.