Reputation: 4118
My target is to pass string arguments to component. Example: I have component that holds and show title and subtitle. I want to pass that strings when I am setting the selector. Something like:
@Component({
selector: 'title-subtitle',
})
in html:
<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>
Upvotes: 2
Views: 9693
Reputation: 1437
To pass a string using @input from a parent component to child component there are two ways.
If you want to pass the string,
<child-component childInput="child input"> </child-component>
If you want to pass the variable from parent component to child component,
<child-component [childInput]="parentInput"> </child-component>
Upvotes: 5
Reputation: 4071
Parent component :
<title-subtitle [childInput]="parentInput">
</title-subtitle>
private parentInput: any;
ngOnInit() {
this.parentInput = 'Hello World';
}
Child component :
import { Component, Input, OnChanges, OnInit } from '@angular/core';
export class ChildComponent implements OnChanges, OnInit {
@Input() private childInput: any;
ngOnInit() {
// When the data is passed instantly, you can access it here.
// You can also use {{childInput}} in your HTML
console.log(this.childInput);
}
ngOnChanges(changes) {
// When the data is async : get the changes when they are ready
// Get @Input data when it's ready
if (changes.childInput) {
console.log(changes.childInput.currentValue);
}
}
}
Note the naming of the properties in the parent HTML.
N.B : You only need the OnInit and/or OnChanges events when you actually need to do something with your data (i.e. Deep cloning it, ...). If you only display it in your HTML with interpolation, there is no need for the events.
N.B 2 : Be aware that this is the SAME OBJECT (same reference) that is sent to your child, which means that if you update a property of your object in your ChildComponent, the changes will also affect the parent. Usually you clone your object to avoid that kind of behavior in the OnInit or OnChanges events.
Upvotes: 3