Modularizando nuestra aplicación de Angular

Si por algo destaca Angular, es por su gran organización. Todo está correctamente separado por ficheros o directorios en función de su función de lo que hace en nuestra aplicación. Cuando un proyecto de Angular va creciendo/tomando envergadura será necesario el crear muchos componentes, directivas, formularios, clases, interfaces, etc.

Para poder continuar manteniendo este orden en nuestros proyectos, Angular, nos provee de módulos que son capaces de agrupar/contener en su interior a componentes, directivas, formularios, clases, interfaces, etc.

Por tanto, los módulos son mecanismo para subdividir en partes nuestra aplicación. El proceso de subdividir una aplicación en módulos recibe el nombre de modularizar/modularización.

Cuando creamos un proyecto, por defecto, tendremos cómo mínimo 1 módulo el AppModule (Root) que será nuestro CoreModule (módulo central). Aunque si responde Yes a ¿Would you like to add Angular routing? (¿Te gustaría agregar un enrutamiento angular?) se nos crearán dos y no un sólo módulo al realizar la creación de la estructura básica de un proyecto.

Por tanto, si tenemos 1 o 2 dependerá de si creamos routing en nuestro módulo. Si le damos a no tenemos uno solamente el por defecto que sería app.module.ts. En el caso que hayamos contestado Yes a la pregunta del routing podemos comprobar que ya tenemos dos módulos.

Si nos fijamos dentro del array de declarations, declaramos el listado de componentes que formaran parte de nuestro modulo. Además de ello, tenemos que exportar el módulo que nos queremos traer al módulo app.module.ts (Root CoreModule) con el fin de poder tener visibilidad/acceso desde nuestro módulo central. Es decir, declarando como export el módulo le indicamos a Angular que tenemos una especie de «acceso» a ese módulo desde otros módulos.

Creando un módulo

Para crear un módulo vamos a la terminal y podemos crearlo a partir de dos formas:

  • Mediante a la instrucción al completo: ng generate module nombreModulo
  • Mediante a la instrucción abreviada: ng g m nombreModulo

El resultado es el mismo. Vamos a ver un ejemplo:

Si abrimos el fichero podemos ver el código de nuestro fichero:

Ahora vamos a añadir un componente sobre nuestro módulo de Angular.

La primera opción para agregar componentes sobre nuestro nuevo modulo hello-world será utilizar:

  • Mediante a la instrucción al completo: ng generate component nombreComponente
  • Mediante a la instrucción abreviada: ng g c nombreComponente

Esta vez, vamos a utilizar la versión más reducida:

Y vemos que se nos ha generado un componente y que nos lo ha auto asignado Angular en nuestro modulo hello-world.module.ts.

Ahora tendremos que importar el módulo hello-world.module.ts sobre nuestro módulo Root app.module.ts de la siguiente manera:

Si copiamos el selector de nuestro componente que se encuentra dentro del módulo hello-world.module.ts y lo pegamos sobre nuestro componente por defecto (que se encuentra declarado dentro del app.module.ts). Podemos observar que nos aparece un error:

Este error se produce debido a que hemos exportado el módulo hello.world.module.ts pero no hemos exportado el component greet.components.ts y, por tanto, para nuestro app.module.ts el módulo hello.world.module.ts es visible y muestra de ello es que lo hemos importado pero el componente greet.component.ts por el momento no es visible.

Para resolver esto, tenemos que agregar un array de exports dentro del módulo:

Si ahora arrancamos la aplicación, podemos ver que ya tenemos conectado y operativo nuestro módulo de hello-world.module.ts:

Eliminando un componente de un módulo

Existe una alternativa mucho más rápida para hacer esto, si borramos el componente greet:

Si intentamos volver a arrancar la aplicación se nos quejará debido a que hemos eliminado el componente pero aún lo tenemos registrado en el array de declaraciones y del de exports:

Para resolver esto, deberíamos eliminar el componente quedando nuestro hello-world.module.ts de la siguiente manera:

Y finalmente eliminaremos el selector del componente de nuestro template:

Añadiendo componentes en nuestro módulo de una manera más rápida

De hecho, si dentro de nuestro módulo hello-world.module.ts eliminamos el array de exports. Podemos observar que estamos en el punto inicial de cuando habíamos creado nuestro módulo hello-world.module.ts:

Y si ahora hacemos ng generate componente –help (en cualquiera de sus versiones la abreviada o la completa). Podemos observar que nos aparece un listado de muchos argumentos que le podemos pasar a nuestro componente durante su creación:

Nosotros vamos a trabajar con:

Si volvemos a crear el componente de greet pero esta vez añadiendo estos argumentos, podemos observar cómo nos crear el exports (en el caso de que no exista) y nos añade a nuestro  componente:

Como podéis ver esta manera es mucho más rápida que la anterior. Y ahora solo nos faltaría repetir el proceso anterior añadir el selector, a nuestro app.component.ts y ya estaría todo (ya que el módulo ya lo habíamos cargado anteriormente sobre el módulo principal app.module.ts.

Espero que os haya gustado y os haya servido para familiarizaros con el concepto de módulos de Angular. Un saludo 🙂

35 comentarios

  1. Gracias totales

  2. This excellent website really has all the information I wanted
    concerning this subject and didn’t know who to ask.

  3. There’s definately a great deal to learn about this
    topic. I like all of the points you have made.

  4. Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment
    didn’t show up. Grrrr… well I’m not writing all that over again. Anyways,
    just wanted to say fantastic blog! quest bars http://bitly.com/3jZgEA2 quest bars

  5. Thank you for another excellent post. Where else could
    anyone get that type of info in such an ideal means of writing?
    I’ve a presentation next week, and I’m at the look for such
    info. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

  6. all the time i used to read smaller articles or reviews which as well clear their motive, and that is
    also happening with this piece of writing which I am reading here.

  7. With havin so much content and articles do you ever run into any issues of plagorism or copyright
    infringement? My blog has a lot of completely unique content
    I’ve either created myself or outsourced but it appears a lot of it is popping
    it up all over the internet without my permission. Do you know
    any ways to help protect against content from being stolen? I’d really appreciate it.

    Review my website: http://www.fotosombra.com.br

  8. I became honored to get a call from a friend as soon as he found
    out the important ideas shared on the site.
    Studying your blog post is a real amazing experience.
    Thanks again for taking into consideration readers just
    like me, and I would like for you the best of achievements like a professional in this field.

    Here is my website; simple skin care

  9. I would like to show some thanks to the writer just for bailing me out of this incident.
    Right after surfing around through the world wide
    web and finding methods which were not helpful, I assumed my life was over.
    Living minus the solutions to the difficulties you have sorted out by way
    of your site is a crucial case, as well as the kind that might have in a wrong way damaged my entire
    career if I hadn’t come across your blog post. Your main natural talent and kindness in playing with all things was precious.
    I’m not sure what I would’ve done if I hadn’t encountered such a solution like this.
    I am able to at this time relish my future. Thank you very much for this specialized and results-oriented help.
    I will not hesitate to endorse your web page to
    anyone who would like guidelines about this issue.

    Also visit my blog http://www.bao10jie.com

  10. May I simply say what a comfort to uncover someone that genuinely understands what they’re discussing on the web.

    You certainly know how to bring a problem to light and make it important.
    A lot more people must read this and understand this side of your story.
    I was surprised you’re not more popular since you most certainly have
    the gift.

    My blog post :: kids smoking

  11. I like this weblog so much, saved to my bookmarks.

    Look into my website improve love making

  12. Hello, you used to write great, but the last several posts have been kinda boring…
    I miss your tremendous writings. Past few posts are just a little bit out of
    track! come on!

    My homepage :: Stephaine

  13. I’m impressed, I must say. Seldom do I encounter a blog that’s equally educative and entertaining, and without a doubt, you’ve hit the nail on the head.
    The problem is something which not enough folks are speaking intelligently about.
    I am very happy I found this during my hunt for something concerning this.

    My web-site; top pre-workout

  14. Wow! Finally I got a webpage from where I know how to really take valuable facts concerning my study and knowledge.

    My blog post – 23.95.102.216

  15. Hi there! I just would like to offer you a big thumbs up for
    your excellent information you have got right here on this post.

    I’ll be returning to your web site for more soon.

  16. Helpful info. Lucky me I found your web site by chance, and I’m surprised
    why this twist of fate did not took place in advance!

    I bookmarked it.

  17. I know this website gives quality depending posts and additional data, is there any
    other web site which presents such data in quality?

    Stop by my webpage … 23.95.102.216

  18. Superb website you have here but I was curious if you knew of any
    message boards that cover the same topics discussed in this
    article? I’d really love to be a part of group where I can get opinions from other knowledgeable individuals that
    share the same interest. If you have any recommendations,
    please let me know. Thank you!

    my website; high quality treatment

  19. I am extremely impressed with your writing skills as well as with the layout on your
    weblog. Is this a paid theme or did you customize it yourself?
    Either way keep up the nice quality writing, it is rare to see a nice blog like this one
    nowadays.

    my site – hemp seeds

  20. I used to be able to find good information from your content.

  21. Awesome blog you have here but I was wanting to know if you knew of any discussion boards that cover the
    same topics talked about in this article? I’d really love to be a part of community where I
    can get responses from other experienced individuals that share the same interest.

    If you have any suggestions, please let me know. Thank you!

  22. Wow! At last I got a weblog from where I be able to really
    get useful data concerning my study and
    knowledge.

  23. Great weblog here! Also your website a lot up fast! What web host
    are you the usage of? Can I get your affiliate hyperlink on your host?
    I desire my site loaded up as fast as yours lol

  24. I used to be suggested this web site by way of my cousin. I’m now not sure whether or not this post is
    written by means of him as no one else understand such specific approximately my trouble.
    You’re amazing! Thanks!

  25. stromectol pills stromectol for humans for sale – oral ivermectin cost
    http://stromectolabc.com/ cost of ivermectin medicine
    ivermectin price usa stromectol1st ivermectin cream 1%

  26. Every weekend i used to visit this website, for the reason that i
    wish for enjoyment, as this this web site conations genuinely nice funny material too.

  27. Wonderful goods from you, man. I’ve understand
    your stuff prior to and you’re just extremely fantastic.
    I really like what you have obtained here, really like what you’re stating and the way in which during which you assert it.
    You make it entertaining and you continue to take care of
    to stay it sensible. I can not wait to read far more
    from you. That is actually a tremendous site.

  28. I’ve read a few excellent stuff here. Certainly value bookmarking for revisiting.
    I surprise how a lot attempt you set to create this type of fantastic informative site.

  29. baccarat online

    26 octubre, 2022 a las 4:13

    I have been looking for articles on these topics for a long time. baccarat online I don’t know how grateful you are for posting on this topic. Thank you for the numerous articles on this site, I will subscribe to those links in my bookmarks and visit them often. Have a nice day

  30. I’ve been looking for photos and articles on this topic over the past few days due to a school assignment, totosite and I’m really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks 😀

  31. Your writing is perfect and complete. casinosite However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?

  32. I loved as much as youll receive carried out right here The sketch is tasteful your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike

  33. Thank you for the auspicious writeup It in fact was a amusement account it Look advanced to far added agreeable from you However how can we communicate

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