将值传递给不同组件中的函数 [英] Pass value to a function in a different Component
问题描述
我有 2 个组件.一个是页面,另一个是在页面上滑动的过渡.直接调用另一个组件中的函数?
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:
父组件:
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";
}
}
子组件:
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);
}
}
推荐答案
Parent=>Child
和Child =>交换数据;父
使用@Input、@ViewChild、EventEmitter、Injector 等...
Parent=>Child
and Child => Parent
using @Input, @ViewChild, EventEmitter, Injector and so on...
service (sharedService)
更新:
我认为您想要的是从父级调用子函数并同时传递数据.为此,您可以使用此处显示的 @ViewChild API
.
注意:您不需要使用@Input.
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
使用 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);
}
}
这篇关于将值传递给不同组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!