Introducción a Pipes + trabajando con Pipes predefinidas

¿Qué son los Pipes?

Las pipes son una especie de tuberías que nos permitirán editar el formato con el que presentamos los valores de variables u objetos que recibimos desde el TypeScript del componente  gracias al binding de String interpolation mostrándolo un formato personalizado en nuestro template y sin ser modificado en el TypeScript de nuestro componente.

Para utilizar un pipe utilizamos la siguiente estructura:  {{value | pipeAUtilizar}}

Un ejemplo podría ser una conversión hacía dólares de la siguiente manera:

Los pipes nos permiten por tanto transformar visualmente nuestros datos, de esta manera podemos mostrar datos con una mejor experiencia de usuario

¿Porque trabajar con Pipes?

La principal ventaja de utilizar  pipes es que te nos vamos a ahorrar mucho código en los componentes, ya que podemos reutilizar código y no tener que escribir tanto código dentro de nuestros componentes facilitará la lectura además del mantenimiento de dicho componente.

Tipos de Pipes:

Dentro de los pipes existen dos tipos:

  • Los pipes predefinidos (Built-in): vienen por defecto en Angular.
  • Los pipes customizados (Custom): existe la posibilidad de crear nuestros propios Pipes que se adapten a nuestras necesidades.

Pipes predefinidos

Existen multitud de pipes en Angular, podéis encontrar más información en su en la web oficial de Angular

Vamos a ver nosotros algunos de ellos (aunque no todos).

UpperCasePipe:

Nos mostrará el valor del binding de String Interpolation en mayúsculas. Pero no modifica el valor de nombre en el componente o en la vista . Sino que lo hace solamente para la presentación de nuestro String Interpolation que va acompañado de dicho pipe.

LowerCasePipe:

Nos mostrará el valor del binding de String Interpolation en minúsculas.

KeyValuePipe:

Hasta ahora hemos estado trabajando siempre con String Interpolation, pero también podemos utilizarlo con alternativas como por ejemplo un *ngFor. KeyValuePipe, transforma Objeto o Mapa en una matriz de pares clave-valor.

Vamos a ver un ejemplo:

Incluso podríamos hacer cosas como esta con muy poco esfuerzo:

JsonPipe:

Convierte el valor en un formato JSON, en nuestro caso un objeto:

CurrencyPipe

Aunque ya hemos trabajado con el currencyPipe, otro ejemplo de este tipo de dato podría ser el siguiente:

Incluso podríamos sacar el símbolo de euros mediante al Pipe de currency:

Cada uno de los pipes que existen como el de currency son un mundo y podemos buscar mucha información de cómo funcionan para la función en concreto que queremos realizar con él.

Un ejemplo de ello, podría ser el poner la divisa que nos muestra el pipe en el lado derecho. Para ello, realizaríamos lo siguiente:

El resultado será:

TitleCasePipe:

Nos permite transformar la primera letra de cada palabra a mayúsculas y el resto de la palabra a minúsculas.

Un ejemplo podría ser:

DatePipe:

Nos permite formatear fechas:

SlicePipe:

Nos permite crear subconjuntos (cortar) un String o un Array de elementos:

DecimalPipe:

Transforma un decimal en una cadena, formateada de acuerdo con las reglas que le establecemos.

La regla la definimos de la siguiente manera:

  • El primer número nos permite definir la cantidad de números enteros.
  • El segundo número nos permite definir la cantidad mínima de números decimales.
  • El tercer número nos permite definir la cantidad máxima de números decimales.

Los números van separados entre si con un .

Vamos a ver otro ejemplo:

Espero que os haya gustado. Un saludo 🙂

44 comentarios

  1. Aw, this was a really nice post. Finding the time and actual effort to produce a very good article… but what can I
    say… I hesitate a whole lot and don’t seem to get anything done.

  2. I’ll right away take hold of your rss as I can’t find your e-mail subscription link or e-newsletter service.
    Do you’ve any? Please permit me understand so that I may just subscribe.
    Thanks.

  3. I do not know whether it’s just me or if perhaps everyone else experiencing problems with your blog.
    It appears as though some of the text in your content are running off the screen.
    Can someone else please comment and let me know if this is happening to them as
    well? This could be a issue with my internet browser because I’ve had this happen before.
    Kudos

  4. Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is important and everything.
    But imagine if you added some great photos or
    video clips to give your posts more, «pop»! Your content is excellent but with pics and
    videos, this site could undeniably be one of the greatest in its field.
    Terrific blog!

  5. Yes! Finally something about a.

  6. Hi there! I know this is kind of off topic but I was wondering if you knew
    where I could find a captcha plugin for my comment form?
    I’m using the same blog platform as yours and
    I’m having trouble finding one? Thanks a lot!

  7. If some one desires expert view on the topic of blogging afterward i
    propose him/her to visit this webpage, Keep up the
    nice job.

  8. Woah! I’m really loving the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s very hard to get that «perfect balance» between superb
    usability and visual appearance. I must say you
    have done a superb job with this. Also, the blog loads extremely quick for me on Safari.
    Outstanding Blog!

  9. Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is valuable and all. But imagine if you
    added some great images or video clips to give your posts
    more, «pop»! Your content is excellent but with images and videos, this blog could definitely be one of the best in its niche.
    Wonderful blog!

  10. drugstore affiliate programs
    online jobs for stay-at-home moms
    affiliate marketing programs for natural supplements
    work from home jobs for beginners in the usa

  11. Buy Metformin on dark web Best deals on Januvia online
    Buy diabetes meds from sketchy Indian pharmacies and save big How to
    buy diabetes meds without getting caught

  12. Outstanding post however , I was wanting to know if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit further. Many thanks!

  13. Hey there I am so happy I found your webpage, I really found you by error, while I was researching on Bing for something else, Anyways I am here
    now and would just like to say thank you for a incredible post and a all
    round entertaining blog (I also love the theme/design), I
    don’t have time to look over it all at the moment but I have bookmarked it and also added in your RSS feeds, so
    when I have time I will be back to read more, Please do keep up the excellent jo.

  14. Asking questions are in fact fastidious thing if you
    are not understanding something entirely, but
    this piece of writing presents pleasant understanding even.

  15. It’s remarkable to pay a visit this site and reading the views of all colleagues on the topic of this post, while I am
    also zealous of getting familiarity.

  16. Greetings! Very helpful advice within this post! It is the little changes that
    make the most significant changes. Many thanks for sharing!

  17. What’s up to every one, since I am actually eager of reading this webpage’s post to be updated daily.
    It includes nice information.

  18. Thank you for another informative blog. Where else could I get that type of information written in such an ideal way? I’ve a project that I’m just now working on, and I’ve been on the look out for such info.

  19. Heya i?m for the first time here. I found this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you aided me.

  20. buy priligy reddit They also reduced the osmotic pressure of the urine by a same factor 30

  21. safe cialis online With a clear view of the reproductive organs, problems can be diagnosed and surgically repaired

  22. I realized more interesting things on this weight loss issue. One particular issue is that good nutrition is tremendously vital whenever dieting. A huge reduction in junk food, sugary meals, fried foods, sweet foods, red meat, and bright flour products could possibly be necessary. Having wastes organisms, and contaminants may prevent aims for losing belly fat. While a number of drugs temporarily solve the problem, the horrible side effects aren’t worth it, plus they never present more than a short-lived solution. This is a known undeniable fact that 95 of dietary fads fail. Thank you for sharing your thinking on this blog.

  23. I have noticed that car insurance companies know the cars and trucks which are prone to accidents as well as other risks. In addition, they know what types of cars are given to higher risk and also the higher risk they’ve already the higher your premium price. Understanding the uncomplicated basics regarding car insurance will allow you to choose the right types of insurance policy that may take care of your wants in case you get involved in an accident. Thank you sharing the ideas in your blog.

  24. This web site is really a walk-by way of for the entire info you needed about this and didn?t know who to ask. Glimpse right here, and you?ll undoubtedly uncover it.

  25. Excellent beat ! I would like to apprentice whilst you amend your web site, how can i subscribe for a blog site? The account aided me a appropriate deal. I had been a little bit acquainted of this your broadcast provided vibrant clear concept

  26. Thanks for your post made here. One thing I would really like to say is always that most professional job areas consider the Bachelor Degree like thejust like the entry level standard for an online certification. Though Associate Certifications are a great way to begin with, completing a person’s Bachelors presents you with many doors to various employment opportunities, there are numerous internet Bachelor Diploma Programs available coming from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions offer you Online variants of their college diplomas but usually for a significantly higher amount of money than the providers that specialize in online college diploma programs.

  27. I have observed that online degree is getting well-liked because obtaining your degree online has turned into a popular selection for many people. Many people have never had a chance to attend a conventional college or university although seek the elevated earning potential and a better job that a Bachelors Degree gives you. Still other individuals might have a degree in one discipline but would want to pursue anything they already have an interest in.

  28. Its such as you read my mind! You appear to understand a lot about this, like you wrote the ebook in it or something. I feel that you simply could do with some p.c. to drive the message home a bit, however instead of that, that is magnificent blog. A great read. I’ll certainly be back.

  29. It’s my opinion that a property foreclosures can have a important effect on the client’s life. Foreclosures can have a Six to few years negative effects on a applicant’s credit report. A new borrower who may have applied for a home loan or virtually any loans for that matter, knows that the actual worse credit rating will be, the more hard it is to acquire a decent personal loan. In addition, it might affect a borrower’s chance to find a good place to let or hire, if that becomes the alternative homes solution. Great blog post.

  30. In this grand scheme of things you actually receive a B- for effort. Where exactly you confused me was first on your facts. You know, people say, details make or break the argument.. And it could not be more accurate right here. Having said that, allow me inform you precisely what did deliver the results. Your text is quite persuasive and this is probably why I am taking the effort to opine. I do not make it a regular habit of doing that. 2nd, despite the fact that I can notice a leaps in reasoning you make, I am not really convinced of how you appear to unite your points which in turn help to make your conclusion. For right now I will, no doubt yield to your point but wish in the foreseeable future you connect the facts better.

  31. I just couldn’t depart your website prior to suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is going to be back often in order to check up on new posts

  32. Nice post. I learn something more difficult on completely different blogs everyday. It is going to at all times be stimulating to learn content from different writers and practice slightly something from their store. I?d prefer to make use of some with the content on my blog whether or not you don?t mind. Natually I?ll offer you a hyperlink on your internet blog. Thanks for sharing.

  33. You should take part in a contest for among the finest blogs on the web. I will recommend this web site!

  34. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.

  35. This is really interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I have shared your web site in my social networks!

  36. Attractive element of content. I simply stumbled upon your weblog and in accession capital to claim that I get actually loved account your weblog posts. Any way I?ll be subscribing to your feeds or even I fulfillment you get admission to consistently quickly.

  37. My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am nervous about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any kind of help would be really appreciated!

  38. Usually I don’t read article on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, quite nice post.

  39. I mastered more new things on this fat loss issue. A single issue is that good nutrition is extremely vital when dieting. A tremendous reduction in junk food, sugary meals, fried foods, sweet foods, pork, and whitened flour products may be necessary. Having wastes harmful bacteria, and toxins may prevent aims for losing fat. While certain drugs quickly solve the matter, the unpleasant side effects are usually not worth it, plus they never give more than a temporary solution. It can be a known proven fact that 95 of fad diets fail. Many thanks sharing your opinions on this weblog.

  40. Hey! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  41. I am really inspired along with your writing skills aswell as with the structure to your blog. Is that this apaid topic or did you modify it your self? Anyway keep up the nice quality writing,it’s uncommon to look a nice blog like this one today..

  42. One thing I’d like to touch upon is that weightloss routine fast can be carried out by the appropriate diet and exercise. Ones size not merely affects appearance, but also the quality of life. Self-esteem, melancholy, health risks, plus physical abilities are affected in extra weight. It is possible to just make everything right and at the same time having a gain. In such a circumstance, a problem may be the primary cause. While an excessive amount of food rather than enough physical exercise are usually responsible, common medical ailments and popular prescriptions might greatly enhance size. Thanks for your post right here.

  43. Thanks for the ideas shared on the blog. Something else I would like to convey is that weight loss is not supposed to be about going on a fad diet and trying to lose as much weight that you can in a few days. The most effective way to lose weight is by having it slowly and gradually and right after some basic guidelines which can assist you to make the most through your attempt to lose weight. You may understand and already be following a few of these tips, but reinforcing knowledge never hurts.

  44. One thing I would like to comment on is that weightloss system fast can be achieved by the suitable diet and exercise. Your size not only affects appearance, but also the overall quality of life. Self-esteem, major depression, health risks, plus physical skills are afflicted in fat gain. It is possible to do everything right whilst still having a gain. Should this happen, a problem may be the primary cause. While an excessive amount food but not enough exercising are usually guilty, common health conditions and widespread prescriptions can greatly enhance size. Thanks alot : ) for your post right here.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar