英文:
Angular: Is it possibe to make a component that looks the same on the fron-end side reusable when needing to do different service calls?
问题
我目前有一个组件,其中有几个输入字段,在失焦时会进行服务调用。在我的应用程序中,相同外观的组件会多次出现,但根据它在哪里使用,它需要执行不同的服务调用。目前,我已经创建了3个在前端看起来相同但执行不同调用的组件。问题是,如果我要更改外观,我必须在三个不同的组件中进行更改,随着应用程序的增长,这将变得更难管理。有没有更好的方法来做这个?
英文:
I currently have a component that has a few input fields and on blur a service call is done. The same looking component occurs a few times in my application but depending on where it is used it needs to do a different service call. Currently I have created 3 different components that look the same on the front-end side but do different calls. The problem with this is if I change the look I have to do it in three different components which will become harder to manage as the application grows. Is there a better way to do this?
答案1
得分: 4
使用 EventEmitter 来捕获失焦事件
在您的组件中声明 EventEmitter 并使用失焦事件来调用它:
@Output() action: EventEmitter<any> = new EventEmitter<any>()
ngOnInit() {
fromEvent(document, 'blur').subscribe(() => action.emit())
}
将 EventEmitter 添加到父组件的模板中:
<child (action)="action()"></child>
在父组件中声明一个函数并调用您需要的服务:
action() { // 调用服务 }
英文:
Use a EventEmitter to catch the blur event
Declare the Emitter in your component and call it with the blur event :
@Output() action: EventEmitter<any> = new EventEmitter<any>()
ngOnInit() {
fromEvent(document, 'blur').subscribe(() => action.emit())
}
Add the EventEmitter into the template of the parent component :
<child (action)="action()"></child>
Declare a function into the parent component and call whater service you need :
action() { // call service}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论