我有两个组件如下,我想从另一个组件调用一个函数。这两个组件都包含在第三个父组件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(孩子):

@Component(
  selector:'com1'
)
export class Component1{
  function1(){...}
}

组件2(父):

@Component(
  selector:'com2',
  template: `<com1 #component1></com1>`
)
export class Component2{
  @ViewChild("component1") component1: Component1;

  function2(){
    this.component1.function1();
  }
}

其他回答

假设第一个组件是DbstatsMainComponent 第二个组件DbstatsGraphComponent。 第一个组件调用第二个方法

<按钮(点击)= " dbgraph.displayTableGraph ()“图> < / >按钮 < dbstats-graph # dbgraph > < / dbstats-graph >

注意子组件上的局部变量#dbgraph,父组件可以使用它来访问它的方法(dbgraph. displaytablegraph())。

我在父组件中使用触发器函数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)

如果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{
}

有关组件间通信的其他选项,请参见组件交互

组件1(孩子):

@Component(
  selector:'com1'
)
export class Component1{
  function1(){...}
}

组件2(父):

@Component(
  selector:'com2',
  template: `<com1 #component1></com1>`
)
export class Component2{
  @ViewChild("component1") component1: Component1;

  function2(){
    this.component1.function1();
  }
}

向component2(或任何具有该方法的组件)添加可注入的装饰器

@Injectable({
    providedIn: 'root'
})

注入到component1 (component2方法将被调用的组件)

constructor(public comp2 : component2) { }

在component1中定义调用component2方法的方法

method1()
{
    this.comp2.method2();
}

组件1和组件2代码如下。

import {Component2} from './Component2';

@Component({
  selector: 'sel-comp1',
  templateUrl: './comp1.html',
  styleUrls: ['./comp1.scss']
})
export class Component1 implements OnInit {
  show = false;
  constructor(public comp2: Component2) { }
method1()
 {
   this.comp2.method2(); 
  }
}


@Component({
  selector: 'sel-comp2',
  templateUrl: './comp2.html',
  styleUrls: ['./comp2.scss']
})
export class Component2 implements OnInit {
  method2()
{
  alert('called comp2 method from comp1');
}