String interpolation en Angular

¿Qué es el Data Biding?

El data biding, es la forma mediante a la cual Angular nos va a permitir mostrar contenido dinámico (que puede cambiar) en vez de contenido estático/fijo (en inglés conocido bajo el termino de harcoded). Por tanto, el databiding es la comunicación, la sincronización entre nuestro template (la vista .html) y nuestra lógica de programación (archivo.ts).

Existen distintos mecanismos para realizar data biding:

Esta comunicación entre los archivos de TypeScript y las templates, las realizamos mediante a DOM:



En este artículo, nos centraremos en el primero, string interpolation.

¿Qué es String interpolation?

La interpolación es el mecanismo más básico de realizar data biding mediante el cual vamos a enviar valores o funciones contenidas dentro de nuestro código de TypeScript de nuestro componente hacía nuestro template (el archivo html). También nos permitirán realizar evaluaciones de expresiones.

El proceso de interpolación es unidireccional y solo puede ir en la siguiente dirección de nuestro TypeScript hacía nuestro document HTML, pero no a la inversa.

En Interpolación se utiliza la sintaxis {{ valor }} como podéis observar, se usan las dobles llaves {{}}, que por su apariencia visual es conocida como sintaxis moustache debido a su similitud con un mostacho o bigote🧔🏻.

Creando un proyecto sobre el que realizar el ejemplo

Vamos a ver un ejemplo. Para ello, creamos e iniciamos un proyecto:

Una vez creado el proyecto, nos situamos en el y lo abrimos con VCS:

Y finalmente arrancamos el proyecto:

Lo que nos abrirá una ventana con nuestra template inicial del proyecto:

Mostrando el valor de una variable con String Interpolation

Finalmente borramos la template que viene por defecto y escribimos un H1 en el que metemos entre {{}} la variable de la que queremos mostrar su valor en la pantalla.

En este caso, si miramos la aplicación, veremos que hemos obtenido el valor correctamente:

También podemos imprimir las propidades de un objeto. Vamos a ver un ejemplo:

En este  caso, es visible dentro del template debido a que la variable nombre está dentro del una clase con export sino no sería visible. Y por tanto, será visible a nivel de nuestro módulo.

Evaluando una expresión con String Interpolation

También podemos realizar operaciones, vamos a ver un ejemplo:

Llamando a una función con String Interpolation

Vamos a realizar dos funciones, numberRandom que nos genere un número del uno al 10 y evenOrOdd que nos indique si el número es par o impar. Si juntamos las llamadas podemos ver el siguiente resultado:

Esto es todo, espero que os haya gustado. ¡Un saludo y hasta la próxima!

69 comentarios

  1. Hi there! This is kind of off topic but I need some
    help from an established blog. Is it difficult to set up your own blog?
    I’m not very techincal but I can figure things out pretty quick.
    I’m thinking about creating my own but I’m not sure where to begin. Do you have any tips or suggestions?

    Thanks

  2. Good day! Would you mind if I share your blog with my zynga group?
    There’s a lot of people that I think would really appreciate your content.
    Please let me know. Thanks

  3. We are a gaggle of volunteers and starting a new scheme in our community.
    Your site provided us with helpful info to work on. You’ve performed an impressive process and our entire group might be thankful to you.
    quest bars http://tinyurl.com/49u8p8w7 quest bars

  4. Excellent blog you have here but I was curious about if
    you knew of any forums that cover the same topics talked about in this article?
    I’d really love to be a part of community where I can get comments from other experienced people
    that share the same interest. If you have any recommendations, please let me know.
    Bless you! ps4 games https://j.mp/3z5HwTp ps4 games

  5. It’s really a cool and useful piece of info. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.
    Like!! Really appreciate you sharing this blog post.Really thank you! Keep writing.

  6. Aw, this was a really nice post. In idea I wish to put in writing like this additionally – taking time and precise effort to make a very good article… but what can I say… I procrastinate alot and on no account seem to get something done.
    It’s a pity you don’t have a donate button! I’d certainly donate to this outstanding blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group. Chat soon!

  7. I think this is among the most important information for me.
    And i am glad reading your article. But want to remark on few general things, The website style is wonderful, the articles is really
    excellent : D. Good job, cheers

  8. Does your website have a contact page? I’m having a tough time locating it but,
    I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.

    Either way, great blog and I look forward to seeing it develop over time.

  9. Hello my friend! I wish to say that this article is amazing, great written and include approximately all vital infos. I¦d like to look more posts like this .

  10. Hi there i am kavin, its my first occasion to commenting anywhere, when i read this article i thought
    i could also make comment due to this sensible paragraph.

  11. And off course, there is driving for a ride-sharing app like Uber (opens
    in new tab) or Lyyft (opens in new tab).

    Feel free to surf to myy web blog: website

  12. I’m gone to tell my little brother, that he should also visit this web site on regular basis to obtain updated from hottest gossip.

  13. I’ve been exploring for a little for any high quality articles or blog posts on this kind of house .

    Exploring in Yahoo I at last stumbled upon this web site.
    Studying this info So i’m satisfied to exhibit that I’ve
    an incredibly good uncanny feeling I came upon just what I
    needed. I such a lot undoubtedly will make sure to do not disregard this site and give it
    a look on a relentless basis.

  14. The solutions we’ve examined go above and beyond to ssatisfy their consumers.

    Here is my site 신용대출

  15. Howdy would you mind stating which blog platform you’re
    working with? I’m planning to start my own blog in the near future but I’m having a hard
    time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different
    then most blogs and I’m looking for something unique.
    P.S Apologies for being off-topic but I had to ask!

  16. Let me give you a thumbs up man. Can I shout out on amazing values and if
    you want to with no joke truthfully see and also share valuable
    info about how to make money yalla lready know follow me my fellow commenters!.

  17. If uploading scratch tickets, please absolutely scratch the game board andd the 22-digit number identified on the front oof the ticket.

    Feel free to visit my web page; PBG파워볼

  18. In the LFS, women on maternity leave are thought
    of employed and absent from perform.

    myblog post: web site

  19. I believe people who wrote this needs true loving because it’s
    a blessing. So let me give back and speak out on change your life and if you want to seriously get to
    hear I will share info about how to get connected to girls easily and quick Don’t
    forget.. I am always here for yall. Bless yall!

  20. If you wawnt to come across out your APR before you apply, Upetart will carry out a soft credit check.

    My web-site; 대환대출

  21. This website is best viewed making use of the browsers listed on the Supported Browsers page.

    Stop by my web blog … 파워볼중계

  22. The content is brand-particular and designed by clients to then be published
    oon social media and other channels.

    my web site;업소 알바

  23. If you win more than $600, tthe lottery will notify you and offer instructions for filling
    out a claim type.

    my homepage … 파워볼중계

  24. “We’ve had a decade where women havfe been underemployed relative to guys,” says Mathur.

    My website … 언니 알바

  25. Woah! I’m really loving the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s hard to get that «perfect balance» between user friendliness
    and visual appearance. I must say that you’ve done a superb job with this.
    In addition, the blog loads super fast for me on Opera.
    Superb Blog!

  26. This revolutionary platform facilitates its borrowers with
    a much lesss than 575 FICO score.

    My web site :: 대환대출

  27. For additional details on accessing your tickets, please see the guidelines above.

    Also visit my website: 동행복권 스피드키노

  28. This is a topic that is near to my heart… Many thanks!
    Where are your contact details though?

  29. I seriously love your site.. Pleasant colors & theme. Did you make this amazing site yourself? Please reply back as I’m planning to create my own personal blog and would like to know where you got this from or just what the theme is called. Thanks!

  30. Great beat ! I wish to apprentice while you amend your site, how can i subscribe for a blog site?
    The account helped me a acceptable deal. I had been tiny bit
    acquainted of this your broadcast offered bright clear idea

  31. Everyone loves it whenever people come together and share ideas. Great site, keep it up!

  32. I will immediately take hold of your rss feed as I can’t to find your
    email subscription hyperlink or newsletter service.
    Do you’ve any? Please permit me know in order that I could subscribe.
    Thanks.

  33. We stumbled over here coming from a different website and thought I might
    check things out. I like what I see so now i’m following you.
    Look forward to exploring your web page for a second time.

  34. Modes of action of aspirin like drugs salicylates inhibit erk activation and integrin dependent neutrophil adhesion cialis from usa pharmacy

  35. MEGAWIN
    https://telegra.ph/MEGAWIN-07-31
    Exploring MEGAWIN Casino: A Premier Online Gaming Experience

    Introduction

    In the rapidly evolving world of online casinos, MEGAWIN stands out as a prominent player, offering a top-notch gaming experience to players worldwide. Boasting an impressive collection of games, generous promotions, and a user-friendly platform, MEGAWIN has gained a reputation as a reliable and entertaining online casino destination. In this article, we will delve into the key features that make MEGAWIN Casino a popular choice among gamers.

    Game Variety and Software Providers

    One of the cornerstones of MEGAWIN’s success is its vast and diverse game library. Catering to the preferences of different players, the casino hosts an array of slots, table games, live dealer games, and more. Whether you’re a fan of classic slots or modern video slots with immersive themes and captivating visuals, MEGAWIN has something to offer.

    To deliver such a vast selection of games, the casino collaborates with some of the most renowned software providers in the industry. Partnerships with companies like Microgaming, NetEnt, Playtech, and Evolution Gaming ensure that players can enjoy high-quality, fair, and engaging gameplay.

    User-Friendly Interface

    Navigating through MEGAWIN’s website is a breeze, even for those new to online casinos. The user-friendly interface is designed to provide a seamless gaming experience. The website’s layout is intuitive, making it easy to find your favorite games, access promotions, and manage your account.

    Additionally, MEGAWIN Casino ensures that its platform is optimized for both desktop and mobile devices. This means players can enjoy their favorite games on the go, without sacrificing the quality of gameplay.

    Security and Fair Play

    A crucial aspect of any reputable online casino is ensuring the safety and security of its players. MEGAWIN takes this responsibility seriously and employs the latest SSL encryption technology to protect sensitive data and financial transactions. Players can rest assured that their personal information remains confidential and secure.

    Furthermore, MEGAWIN operates with a valid gambling license from a respected regulatory authority, which ensures that the casino adheres to strict standards of fairness and transparency. The games’ outcomes are determined by a certified random number generator (RNG), guaranteeing fair play for all users.

  36. Im obliged for the blog.Really looking forward to read more. Want more.

  37. I am so grateful for your article.Thanks Again. Really Cool.

  38. Thanks for the article. Really Cool.

  39. Really enjoyed this article post.Really looking forward to read more.

  40. Muchos Gracias for your article.Thanks Again. Great.

  41. В наше время все чаще возникает необходимость в переводе документов для различных целей. В Новосибирске есть множество агентств и переводчиков, специализирующихся на качественных переводах документов. Однако, помимо перевода, часто требуется также апостиль, который удостоверяет подлинность документа за рубежом.

    Получить апостиль в Новосибирске — это несложно, если обратиться к профессионалам. Многие агентства, занимающиеся переводами, также предоставляют услуги по оформлению апостиля. Это удобно, т.к. можно сделать все необходимые процедуры в одном месте.

    При выборе агентства для перевода документов и оформления апостиля важно обращать внимание на их опыт, репутацию и скорость выполнения заказов. Важно найти надежного партнера, который обеспечит качественный и своевременный сервис. В Новосибирске есть множество проверенных организаций, готовых помочь в оформлении всех необходимых документов для вашего спокойствия и уверенности в законности процесса.

    https://salda.ws/meet/notes.php?id=12681

  42. Wow, great blog.Really thank you! Really Cool.

  43. Great article.Really looking forward to read more. Really Cool.

  44. Really informative article.Really looking forward to read more.

  45. Thanks so much for the blog.Really thank you! Awesome.

  46. Appreciate you sharing, great blog post.Really thank you! Fantastic.

  47. Really appreciate you sharing this blog.Really thank you! Much obliged.

  48. I appreciate you sharing this blog article.Really thank you! Cool.

  49. Thanks a lot for the post.Much thanks again. Keep writing.

  50. ТолMuch – ваш надежный партнер в переводе документов. Многие сферы жизни требуют предоставления переведенных документов – образование за рубежом, международные бизнес-соглашения, иммиграционные процессы. Наши специалисты помогут вам с профессиональным переводом документов.

    Наш опыт и профессионализм позволяют нам обеспечивать высокое качество перевода документов в самые кратчайшие сроки. Мы понимаем, насколько важна точность и грамотность в этом деле. Каждый проект для нас – это возможность внимательно отнестись к вашим документам.

    Сделайте шаг к успешному будущему с нами. Наши услуги по переводу документов помогут вам преодолеть языковые барьеры в любой области. Доверьтесь переводу документов профессионалам. Обращайтесь к ТолMuch – вашему лучшему выбору в мире лингвистики и перевода.
    перевод документов
    #переводдокументов #ТолMuch #язык #бизнес

  51. Awesome blog post.Much thanks again.

  52. Thank you ever so for you post.Thanks Again. Really Cool.

  53. ТолMuch – ваш надежный партнер в переводе документов. Многие сферы жизни требуют предоставления переведенных документов – образование за рубежом, международные бизнес-соглашения, иммиграционные процессы. Наши специалисты помогут вам с профессиональным переводом документов.

    Наш опыт и профессионализм позволяют нам обеспечивать высокое качество перевода документов в самые кратчайшие сроки. Мы понимаем, насколько важна точность и грамотность в этом деле. Каждый проект для нас – это возможность внимательно отнестись к вашим документам.

    Сделайте шаг к успешному будущему с нами. Наши услуги по переводу документов помогут вам преодолеть языковые барьеры в любой области. Доверьтесь переводу документов профессионалам. Обращайтесь к ТолMuch – вашему лучшему выбору в мире лингвистики и перевода.

    #переводдокументов #ТолMuch #язык #бизнес

  54. Hey, thanks for the blog post.Thanks Again. Want more.

  55. Enjoyed every bit of your post. Keep writing.

  56. Thanks so much for the article post.Really looking forward to read more. Awesome.

  57. Thank you ever so for you blog.Thanks Again. Fantastic.

  58. I really liked your blog article. Cool.

  59. I really like and appreciate your blog post. Will read on…

  60. Thank you ever so for you blog. Keep writing.

  61. Thanks for the blog.Really looking forward to read more. Much obliged.

  62. Appreciate you sharing, great blog post.Thanks Again. Really Cool.

  63. Готов перейти от идей к реальности? Шьем брендовые свитшоты вместе! Учись создавать стильные вещи и покорять мир своим талантом на новом мастер-классе. Не упусти возможность стать модным гуру! Зарегистрироваться сейчас https://u.to/zQWJIA

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