我是 Angular 新手,我计划在我的应用程序上创建一个动态函数。我想要一个动态函数(例如,调用父组件时,子组件上的buttonclick函数将执行console.log,而当调用parent2组件时,buttonclick函数将执行警报对话框)。是否可以为每个组件调用具有不同实现的动态函数?我该怎么做?
child.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template : '<button click()="dynamicFunction()">Click!</button>',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
dynamicFunction(){
//do nothing
}
ngOnInit() {
}
}
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template : '<app-child></app-child>',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor() { }
dynamicFunction(){
console.log('parent 1 clicked');
}
ngOnInit() {
}
}
parent2.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent2',
template : '<app-child></app-child>',
styleUrls: ['./parentTwo.component.css']
})
export class ParentTwoComponent implements OnInit {
constructor() { }
dynamicFunction(){
alert('parent 2 was called');
}
ngOnInit() {
}
}
最佳答案
在 Angular 使用服务中共享的功能
在 Angular 中,您可以创建服务并在所有功能中作为提供者共享该服务。服务中的方法/函数可以从任何组件(包括子组件或非子组件)调用
关于javascript - 如何在 Angular 组件之间调用动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58193703/