angular - 如何在Angular中从外部调用组件的功能
问题描述
如何从父组件调用 Angular 组件的功能。我在这里想要实现的是在关闭父组件中的模式之前获得确认消息。
子组件内的函数将检查未保存的更改。如果有任何未保存的更改,孩子将调用另一个模态进行确认。
在从这个内部模态确认后,我将再次回调 parat 中的模态以调用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();
}
}
推荐阅读
- .net-core - .net core 可以检测 WSL 执行的操作系统吗?
- css - 如何在响应式设计中使用百分比率而不是 px 率?
- listview - 有没有办法在水平滚动视图中对特定偏移进行动画处理?
- python-3.x - 如何拆分数据框并绘制一些列
- javascript - 为什么我的背景图片隐藏了我的键码生成器?
- python - 'DataFrame' 对象没有属性 'types'
- node.js - Node.js Express 应用程序只能通过 localhost 工作,不能通过网络工作(找不到文件或目录)?
- android - 错误类型错误:无法读取未定义离子 4 的属性“用户名”
- batch-file - 如果 NIRCMD.exe 失败,则返回 ErrorLevel 或控制台消息
- oop - 如何为泛型类型建模