Reputation: 2859
I have 2 components. one is a page and the other is a transition that slides over the page.. I wish to pass a value to a function in the transitionComponent but cant figure it out.. is @input the best way to do this or is there another way to directly call a function in another component ?
Edited with code example - I have slimmed down the main component to just focus on passing this value:
parent component:
import {Component, ElementRef, OnInit} from '@angular/core';
import {TransitionComponent} from '../../PageLoader/TransitionComponent';
@Component({
selector: 'home',
templateUrl: './app/components/Homepage/list/index.html',
directives: [ TransitionComponent]
})
export class HomepageListComponent implements OnInit {
transitionState: string;
constructor() {
this.transitionState = this.transitionState;
}
ngOnInit() {
this.transitionState = "test";
}
}
Child Component:
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'the-loader',
template: `<div class="loader"></div>`,
styles: [`
.loader {
background-color: black;
height: 100%;
width:100%;
position:absolute;
top:0;
left:0;
z-index:99999;
}
`]
})
export class TransitionComponent {
@Input() transitionState;
transitionStatus(transitionState) {
alert(transitionState);
}
}
Upvotes: 0
Views: 1857
Reputation: 55443
Parent=>Child
and Child => Parent
using @Input, @ViewChild, EventEmitter, Injector and so on...
service (sharedService)
Update:
I think what you want is to call a child function from parent and pass the data at a same time. For that you can use @ViewChild API
shown here.
NOTE: you don't need to use @Input.
https://plnkr.co/edit/VaddcH?p=preview
with RC - https://plnkr.co/edit/iRLGfgO4zwUXDXzw9ot7?p=preview
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; // <---ViewChild added
import {TransitionComponent} from '../../PageLoader/TransitionComponent';
@Component({
selector: 'home',
templateUrl: './app/components/Homepage/list/index.html',
directives: [ TransitionComponent]
})
export class HomepageListComponent{
@ViewChild(TransitionComponent) vc:TransitionComponent;
ngAfterViewInit()
{
this.vc.transitionStatus('Angular2');
}
}
export class TransitionComponent {
transitionStatus(transitionState:string) {
alert(transitionState);
}
}
Upvotes: 3
Reputation: 6826
In parent-child relatinship you can use:
ViewChild: when a parent component needs to access a member of it's child component, you can for example call a child's function from the parent.
@Input: allows you to pass a value from the parent to the child.
In your case I would use @input aprouch
Upvotes: 0