Simplificando la lógica de vista en Angular
Mar 02 2023
Recientemente, tuve que implementar una vista emergente con muchas variaciones basadas en condiciones complejas. Usar ngSwitch, en este caso, era imposible, y usar ngIf es ilegible y detallado.
Recientemente, tuve que implementar una vista emergente con muchas variaciones basadas en condiciones complejas. Usar ngSwitch, en este caso, era imposible, y el uso ngIfes ilegible y detallado.
Así es como decidí abordar este problema. El primer paso fue crear una directiva llamada TemplateIdDirective:
@Directive({
selector: 'ng-template[id]',
standalone: true
})
export class TemplateIdDirective {
@Input() id: string;
tpl = inject(TemplateRef);
}
<-- trace-information.component.html -->
<div>
<p>{{ header }}</p>
<ng-template [ngTemplateOutlet]="body"></ng-template>
</div>
<ng-template id="variation-one">...</ng-template>
<ng-template id="variation-two">...</ng-template>
<ng-template id="variation-three">...</ng-template>
<ng-template id="variation-four">...</ng-template>
<ng-template id="variation-five">...</ng-template>
@Component({
selector: 'app-trace-information',
standalone: true,
imports: [TemplateIdDirective],
templateUrl: './trace-information.component.html'
})
export class TraceInformationComponent {
header = '';
@Input() traceInfo: TraceInfo;
@ViewChildren(TemplateIdDirective)
templates: QueryList<TemplateIdDirective>;
private cdr = inject(ChangeDetectorRef);
ngAfterViewInit() {
this.resolveView();
}
private resolveView() {
// All the complex conditions are defined here.
// In real life is way more complicated than that.
// This is only for illustration
if(...) {
this.header = '...';
this.body = this.getTemplate('variation-one');
} else if(...) {
if(...) {
this.header = '...';
this.body = this.getTemplate('variation-two');
} else {
this.header = '...';
this.body = this.getTemplate('variation-three');
}
}
this.cdr.detectChanges();
}
private getTemplate(id: string) {
return this.templates.find((tpl) => tpl.id === id).tpl;
}
}
¡ Sígueme en Medium o Twitter para leer más sobre Angular y JS!

![¿Qué es una lista vinculada, de todos modos? [Parte 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































