繁体   English   中英

如何在Angular中从外部调用组件的功能

[英]How to call a function of component from outside in Angular

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

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

在从这个内部模态确认后,我将再次回调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>

要从其父级调用子级函数,可以使用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();
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM