Angular:指令与管道 [英] Angular: Directives vs Pipes

查看:69
本文介绍了Angular:指令与管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建和使用指令与创建和使用管道有什么相关的参数。

此问题源于的场景是货币输入和输出。

The scenario this question stems from is around currency input and output.

如果用户需要输入货币,为什么不创建/使用将输入解析为格式化货币字符串的指令?另一种选择是接收该字符串,并通过如下所示的管道显示它:

If a user needs to input a currency, why not create/use a directive that parses the input into a formatted currency string? The other option is to take in that string, and display it through a pipe like so:

<input type="text" #val (keydown)="currencyVal=val.value" />
<h3>{{currencyVal | currency}}</h3>

vs

// Where mask-money is a directive that filters the 
//input to a formatted currency string
<input type ="text" mask-money (keydown)="currencyVal=val.value" />
<h3>{{currencyVal}}</h3>

另一方面,管道可以在控制器/组件中使用,由输入过滤器来过滤价值。

On the other hand, a pipe can be used in the controller/component triggered by an input to filter the value.

我可以问一些关于它的问题,但我基本上想知道: 每个人的论据是什么?

I could ask a ton of questions about it, but I basically want to know: what are the arguments for each?

推荐答案

为了用最简单的术语来说明一点,我会说管道是操纵数据,而指令更多用于 DOM操作

To bring it to the point in the most simple terms, i would say a pipe is to manipulate data, while a directive is more for DOM manipulation.

管道将数据作为输入,转换并以另一种方式输出此数据。

A pipe gets data as an input, transforms it and outputs this data in another way.

指令得到一个附加的DOM元素,并通过某种功能对其进行增强。

A directive gets a DOM element it's "attached" to and enhances it with some kind of features.

当然,你会发现两个都有意义的例子(拿组件考虑在内,你有三种结构类型可供选择),这更多是你选择的偏好问题。

Of course you will find examples where both make sense (take the Components into account and you have three structure types to decide between) and it's more of a question of preference which you choose.

In您的示例是使用管道。假设您想以粗体文本显示货币值,并使用图像图标作为货币符号,您可能需要指令

In your example you would use a pipe. Let's say you want to show the currency value in bold text and use an image-icon as a currency symbol you probably take a directive

这篇关于Angular:指令与管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆