我有两个组件如下,我想从另一个组件调用一个函数。这两个组件都包含在第三个父组件using指令中。
组件1:
@component(
selector:'com1'
)
export class com1{
function1(){...}
}
组件2:
@component(
selector:'com2'
)
export class com2{
function2(){...
// i want to call function 1 from com1 here
}
}
我尝试过使用@input和@output,但我不清楚如何使用它以及如何调用该函数,有人能帮忙吗?
如果com1和com2是兄弟姐妹,可以使用
@component({
selector:'com1',
})
export class com1{
function1(){...}
}
com2使用EventEmitter触发一个事件
@component({
selector:'com2',
template: `<button (click)="function2()">click</button>`
)
export class com2{
@Output() myEvent = new EventEmitter();
function2(){...
this.myEvent.emit(null)
}
}
在这里,父组件添加了一个事件绑定来监听myEvent事件,然后在发生此类事件时调用com1.function1()。
#com1是一个模板变量,允许从模板的其他地方引用这个元素。我们使用这个来使function1()成为com2的myEvent的事件处理程序:
@component({
selector:'parent',
template: `<com1 #com1></com1><com2 (myEvent)="com1.function1()"></com2>`
)
export class com2{
}
有关组件间通信的其他选项,请参见组件交互
这取决于你的组件之间的关系(父/子),但最好的/通用的方式来实现通信组件是使用共享服务。
更多细节请参阅以下文档:
https://angular.io/docs/ts/latest/cookbook/component-communication.html !# bidirectional-service
也就是说,你可以使用下面的方法将com1的实例提供给com2:
<div>
<com1 #com1>...</com1>
<com2 [com1ref]="com1">...</com2>
</div>
在com2中,您可以使用以下命令:
@Component({
selector:'com2'
})
export class com2{
@Input()
com1ref:com1;
function2(){
// i want to call function 1 from com1 here
this.com1ref.function1();
}
}
使用Dataservice,我们可以从另一个组件调用该函数
Component1:我们调用该函数的组件
constructor( public bookmarkRoot: dataService ) { }
onClick(){
this.bookmarkRoot.callToggle.next( true );
}
dataservice.ts
import { Injectable } from '@angular/core';
@Injectable()
export class dataService {
callToggle = new Subject();
}
Component2:包含函数的组件
constructor( public bookmarkRoot: dataService ) {
this.bookmarkRoot.callToggle.subscribe(( data ) => {
this.closeDrawer();
} )
}
closeDrawer() {
console.log("this is called")
}
你可以从组件2中访问组件1的方法。
componentOne
ngOnInit() {}
public testCall(){
alert("I am here..");
}
componentTwo
import { oneComponent } from '../one.component';
@Component({
providers:[oneComponent ],
selector: 'app-two',
templateUrl: ...
}
constructor(private comp: oneComponent ) { }
public callMe(): void {
this.comp.testCall();
}
componentTwo html文件
<button (click)="callMe()">click</button>