如何在Angular中从外部调用组件函数

时间:2019-04-14 12:10:34

标签: angular typescript angular-directive

如何从parant组件中调用Angular组件的功能。我在这里想要实现的是在关闭parant组件中的模式之前获得一条确认消息。

子组件内部的功能将检查未保存的更改。如果有未保存的更改,孩子将调用另一个模式进行确认。

在从此内部模式确认后,我将再次在对等体中再次调用该模式以调用this.autoPopupUnratedModal.dismiss()调用

这有点混乱,但是我找不到一个明确的解决方案。 尽管这个问题有很多答案,但是似乎没有什么可以解决我的问题。也许我看错了来源。

<modal #autoPopupUnratedModal size="lg" [keyboard]="'false'" [backdrop]="'static'">
    <modal-header [show-close]="true">
        <h2 class="modal-title">List of unrated jobs</h2>
    </modal-header>
    <modal-body>

        <unrated-job-notification #unratedNofitication
                 [(onDiscard)]="isCloseNotification"
                 (onDiscard)="onCloseConfirmation($event)">
        </unrated-job-notification>

    </modal-body>
    <modal-footer [show-default-buttons]="false">
        <button type="button" class="btn" (click)="rateAnotherTime()">
           Rate another time
        </button>
    </modal-footer>
</modal>

1 个答案:

答案 0 :(得分:0)

要从父级调用子级函数,可以使用viewchild获取其引用或具有rxjs可观察的实现的服务。

使用viewchild可以解决您的问题 这是一个示例子项和父项组件,其中父项正在调用其子项的foo()方法

子组件

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  constructor() { }

  foo() {
    // I will be called from my parent
  }

}

父项

<app-child #child_comp></app-child>




import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  @ViewChild('child_comp') childComp;
  constructor() { }

  ngOnInit() {
    this.childComp.foo();
  }

}