Structural Directive with API Condition
1. Create the Directive
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appShowIf]'
})
export class ShowIfDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input() set appShowIf(condition: boolean) {
this.viewContainer.clear();
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
}
2. Usage in HTML with API Response
<div *appShowIf="apiSuccess">
API returned success — show this content!
</div>
3. In Component.ts
apiSuccess = false;
ngOnInit() {
this.http.get('https://api.example.com/data').subscribe({
next: res => this.apiSuccess = true,
error: err => this.apiSuccess = false
});
}