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

问题描述 投票:0回答:4

我只是无法理解,

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

angular typescript parent-child communication
4个回答
4
投票

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

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

export class ParentComponent {

  @ViewChild(ChildComponent)
  childComponent: ChildComponent;

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

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了。如果您需要在点击中执行其他操作,您甚至可以将子变量传递给父级内的函数


0
投票

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();
     }
   }

你总是会调用找到的第一个元素的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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.