如何从父组件调用子组件的功能

时间:2019-04-18 07:16:27

标签: angular typescript parent-child communication

我就是听不懂

单击父组件中的按钮时如何在子组件内部调用函数?

4 个答案:

答案 0 :(得分:4)

使用@ViewChild装饰器来访问您的子组件。

import { ChildComponent } './child.component'
import { ViewChild } from '@angular/core';

export class ParentComponent {

  @ViewChild(ChildComponent)
  childComponent: ChildComponent;

  someMethod() {
     this.childComponent.someFunction();
  }
}

答案 1 :(得分:2)

如果这是您的父模板:

<button (click)="onClick()">Click</button>
<div>
  <child-component></child-component>
</div>

您可以在父级中使用@ViewChild()

export class ParentComponent {
  @ViewChild(ChildComponent)
  child: ChildComponent;

  onClick(): void {
    if (this.child) {
      this.child.someFunction();
    }
  }
}

另一种方法是直接在模板中执行此操作:

您可以将模板更改为此:

<button (click)="child.someFunction()">Click</button>
<div>
  <child-component #child></child-component>
</div>

然后,无需使用@ViewChild。如果您需要在点击中执行其他操作,甚至可以将子变量传递给父代内部的函数

答案 2 :(得分:0)

答案 3 :(得分:0)

正如其他人所说,您可以使用@ViewChild。但是请注意,通过这种方式,您将在该类型的第一个子对象上调用函数 。 如果您有这样的子组件:

    @Component({
      selector: 'app-my-child',
      template: '<p>I am the child number {{id}} </p>'
    })
    export class MyChildComponent  {

      @Input() id: number;
      constructor() { }

      print() {
        console.log('Action from id ' + this.id);
      }
    }

和这样的父组件:

   <button (click)="printChild()">Print!</button>
   <app-my-child  [id]="1"></app-my-child>
   <app-my-child  [id]="2"></app-my-child>

引用人

   @Component({
     selector: 'app-internal',
     templateUrl: './internal.component.html' 
   })
   export class InternalComponent {
     @ViewChild(MyChildComponent) child: MyChildComponent;
     constructor() { }
     printChild() {
       this.child.print();
     }
   }

您将始终调用找到的第一个元素的打印功能。因此,如果交换两个MyChildComponents,将打印“ ID为2的操作”。

要避免这种情况,您可以像这样明确标识目标组件:

   <button (click)="id2.print()">Print!</button>
   <app-my-child #id1 [id]="1"></app-my-child>
   <app-my-child  #id2 [id]="2"></app-my-child>

如果您不想在组件类中引用它们或使用相反的方法:

    @ViewChild('id1') child1 : MyChildComponentComponent;


   printChild() {
      this.child1.print();
    }
相关问题