¿Se pueden usar enlaces de ancla en Angular? Así se hace.

Guía práctica para usar enlaces de ancla en Angular con routerLink y fragment, manteniendo la ruta actual, activando anchorScrolling y desplazamiento suave para navegar entre secciones.

12 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

¿Se pueden usar enlaces de ancla en Angular? La respuesta es sí, pero no funciona exactamente igual que en HTML puro. En una página estática bastaría con <a href=#mi-id>Ir a sección</a> y un elemento con id=mi-id, pero en Angular hay que integrar el enrutador para que la navegación y el historial funcionen correctamente.

Por qué fallan los enlaces normales en Angular: muchas veces vemos una tabla de contenidos con enlaces que parecen apuntar a secciones internas pero al hacer clic no ocurre nada porque el enlace no está configurado para que Angular maneje el fragmento. En un proyecto Angular no es suficiente poner href, hay que usar las herramientas del router para mantener la ruta actual y aplicar el fragmento.

Cómo añadir routerLink y fragmentos: la solución estándar consiste en usar la directiva routerLink combinada con el input fragment. En el template se usan enlaces como <a [routerLink]=[] fragment=links>Añadir un enlace</a> que indican al router que permanezca en la ruta actual y establezca el fragmento en la URL. Si se dejan los atributos vacíos o mal formados la navegación puede cambiar la ruta en lugar de quedarse en la página.

Importar RouterLink en el componente: para usar la directiva en un componente standalone hay que importar RouterLink en el array imports. Por ejemplo mostraría algo como import { RouterLink } from @angular/router ; @Component({ selector: app-page, imports: [ RouterLink ] }) export class PageComponent { } Esto permite usar [routerLink] y fragment en las etiquetas del template.

Solución para quedarse en la ruta actual: la clave práctica es vincular routerLink a un array vacío escribiendo [routerLink]=[] y pasar fragment con el id objetivo. Así no se produce un cambio de ruta y solo se modifica la parte de fragmento de la URL, por ejemplo <a [routerLink]=[] fragment=scrolling>Ir a desplazamiento</a>.

Habilitar anchor scrolling en el router: además de los enlaces hay que decirle al router que haga scroll cuando exista un fragmento. En la configuración de arranque se incorpora withInMemoryScrolling y se activa anchorScrolling. En un bootstrapApplication o en provideRouter hay que añadir withInMemoryScrolling({ anchorScrolling: enabled }) para que Angular busque el id en la página y realice el desplazamiento al fragmento indicado.

Suavizar el desplazamiento con CSS: una mejora visual sencilla es activar el comportamiento suave con una línea de CSS global. En el archivo de estilos globales añadir html { scroll-behavior: smooth; } para que el salto entre secciones se vea pulido y natural.

Resumen rápido: usar [routerLink]=[] fragment=miId para cada enlace que salte dentro de la misma página, importar RouterLink en el componente si es necesario, habilitar con withInMemoryScrolling la opción anchorScrolling del router y añadir scroll-behavior: smooth para un desplazamiento agradable. Con eso los enlaces funcionan, el historial mantiene los fragmentos y la experiencia de usuario mejora.

En Q2BSTUDIO somos especialistas en desarrollo de software y aplicaciones a medida y podemos ayudarte a integrar buenas prácticas Angular en proyectos completos. Si buscas software a medida o aplicaciones a medida con arquitectura robusta, o quieres potenciar tus soluciones con inteligencia artificial y agentes IA para empresas, contamos con experiencia en servicios cloud aws y azure, ciberseguridad, servicios inteligencia de negocio y power bi, automatización de procesos y más para llevar tu producto al siguiente nivel.

Si necesitas consultoría para implementar navegación por fragmentos, optimizar la accesibilidad o desplegar soluciones seguras en la nube, contacta con nuestro equipo y convertimos tu idea en una aplicación escalable y segura que incorpora las mejores prácticas de Angular y experiencia de usuario.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.