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?

huangapple go评论70阅读模式
英文:

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&lt;any&gt; = new EventEmitter&lt;any&gt;()

ngOnInit() {
  fromEvent(document, &#39;blur&#39;).subscribe(() =&gt; action.emit())
}

Add the EventEmitter into the template of the parent component :

&lt;child (action)=&quot;action()&quot;&gt;&lt;/child&gt;

Declare a function into the parent component and call whater service you need :

action() { // call service}

huangapple
  • 本文由 发表于 2020年1月3日 20:05:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定