我有两个组件如下,我想从另一个组件调用一个函数。这两个组件都包含在第三个父组件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,但我不清楚如何使用它以及如何调用该函数,有人能帮忙吗?
我在父组件中使用触发器函数1(子函数),如下所示:
组件1(孩子):
@Component(
selector:'com1'
)
export class Component1{
function1(){...}
}
组件2(父):
@Component(
selector:'com2',
template: `<button (click)="component1.function1()"
<com1 #component1></com1>`
)
export class Component2{
}
#component1是一个模板变量。您可以用任何名称替换它。(例:# hello1)
使用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")
}
这取决于你的组件之间的关系(父/子),但最好的/通用的方式来实现通信组件是使用共享服务。
更多细节请参阅以下文档:
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();
}
}
你可以从组件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>