Uproszczenie logiki widoku w Angular
Mar 02 2023
Ostatnio musiałem zaimplementować widok popover z wieloma odmianami opartymi na złożonych warunkach. Użycie ngSwitch w tym przypadku było niemożliwe, a użycie ngIf jest nieczytelne i gadatliwe.
Ostatnio musiałem zaimplementować widok popover z wieloma odmianami opartymi na złożonych warunkach. Użycie ngSwitchw tym przypadku było niemożliwe, a użycie ngIfjest nieczytelne i gadatliwe.
Oto jak postanowiłem podejść do tego problemu. Pierwszym krokiem było stworzenie dyrektywy o nazwie 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;
}
}
Śledź mnie na Medium lub Twitterze, aby dowiedzieć się więcej o Angular i JS!

![Czym w ogóle jest lista połączona? [Część 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































