Angular 20: Adiós a *ngIf y *ngFor, Hola @if y @for

Descubre Angular 20 y su nueva sintaxis de control de flujo con @if, @for y @switch, migración rápida y plantillas más legibles, y cómo Q2BSTUDIO impulsa tus proyectos con desarrollo a medida, IA y seguridad.

10 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Angular 20 ha dicho adiós a las directivas estructurales clásicas como *ngIf, *ngFor y *ngSwitch y presenta una sintaxis moderna de control de flujo que se parece más a JavaScript y TypeScript. En este artículo reescrito explico los cambios, muestro ejemplos de migración y explico por qué esta novedad mejora la legibilidad y el mantenimiento de las plantillas. Además, en Q2BSTUDIO somos especialistas en desarrollo de software a medida, aplicaciones a medida y soluciones de inteligencia artificial y ciberseguridad, por lo que te ayudamos a adaptar tus proyectos a las últimas novedades tecnológicas.

Por qué el cambio: durante años Angular usó directivas estructurales como *ngIf, *ngFor y *ngSwitch para controlar el DOM. Aunque potentes, tenían limitaciones: la sintaxis era diferente al código JS/TS habitual, exigían el prefijo * y envolvían elementos en ng-template ocultos, lo que dificultaba la lectura en plantillas complejas. La nueva sintaxis en bloque resuelve esto haciendo que las plantillas se sientan más como escribir código normal.

1. Renderizado condicional con @if

Forma antigua deprecada <div *ngIf=isLoggedIn; else guest> Bienvenido de nuevo, {{ userName }}! </div> <ng-template #guest> <p>Por favor inicia sesión</p> </ng-template>

Nueva forma en Angular 20 y superior @if (isLoggedIn) { <div>Bienvenido de nuevo, {{ userName }}!</div> } @else { <p>Por favor inicia sesión</p> }

La nueva sintaxis es más limpia, no requiere plantillas ng-template adicionales y permite else if para múltiples condiciones.

2. Bucles con @for

Forma antigua deprecada <ul> <li *ngFor=let item of items; index as i; trackBy: trackByFn> {{ i+1 }}. {{ item }} </li> </ul>

Nueva forma en Angular 20 y superior <ul> @for (item of items; track trackByFn(item); let i = $index) { <li>{{ i+1 }}. {{ item }}</li> } </ul>

La sintaxis en bloque recuerda a for of, incorpora variables como $index, $count, $first y $last, y reemplaza trackBy por una llamada track más natural.

3. Casos switch con @switch

Forma antigua deprecada <div [ngSwitch]=role> <p *ngSwitchCase=admin>Acceso administrador</p> <p *ngSwitchCase=user>Acceso usuario</p> <p *ngSwitchDefault>Acceso invitado</p> </div>

Nueva forma en Angular 20 y superior @switch (role) { @case (admin) { <p>Acceso administrador</p> } @case (user) { <p>Acceso usuario</p> } @default { <p>Acceso invitado</p> } }

Estructura clara que se asemeja a un switch real y facilita el manejo de múltiples casos.

4. Migración facilitada

Angular ofrece una herramienta de migración para actualizar automáticamente tus plantillas: ng update @angular/core --name=control-flow-migration Esta orden reemplazará las sintaxis obsoletas por sus contrapartes modernas.

5. Ejemplo: componente completo en Angular 20

<h1>Panel de usuario</h1> @if (isLoggedIn) { <p>Bienvenido, {{ userName }}</p> <ul> @for (task of tasks; let i = $index) { <li>{{ i+1 }}. {{ task }}</li> } </ul> @switch (role) { @case (isAdmin) { <button>Gestionar usuarios</button> } @case (isEditor) { <button>Editar contenido</button> } @default { <p>Acceso básico</p> } } } @else { <p>Por favor inicia sesión para acceder a tu panel.</p> }

Beneficios clave de la nueva sintaxis: mayor limpieza y legibilidad al acercarse al estilo de TypeScript, eliminación del prefijo *, ausencia de envoltorios ng-template ocultos, mejor tooling con diagnósticos del compilador y soporte de editores, y una sintaxis más preparada para el futuro.

En Q2BSTUDIO combinamos experiencia en Angular y buenas prácticas de desarrollo con servicios profesionales en aplicaciones a medida y software a medida. Si necesitas modernizar tus frontends, optimizar migraciones o integrar inteligencia artificial en tus interfaces, podemos ayudarte. Conecta tu proyecto con nuestros servicios de desarrollo de aplicaciones y software a medida o explora soluciones de inteligencia artificial para empresas. También ofrecemos experiencia en ciberseguridad, pentesting, servicios cloud aws y azure, servicios de inteligencia de negocio y Power BI, agentes IA y automatización de procesos para que tu solución sea segura, escalable y orientada a resultados.

Si quieres que adaptamos tus plantillas Angular 20, optimicemos rendimiento o integremos agentes IA en tu producto, en Q2BSTUDIO somos tu partner tecnológico. Contáctanos y te asesoramos en estrategia, migración y desarrollo full stack con enfoque en seguridad y rendimiento.

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.

Live Chat