This is my solution with Angular 13. I plan to create a pagination component so ignore the name.
Directive:
import {Directive, EventEmitter, Input, OnInit, Output, TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[appPaginate]'
})
export class PaginateDirective implements OnInit {
@Output() newItemEvent: EventEmitter<string> = new EventEmitter<string>()
constructor( private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
ngOnInit() {
}
@Input() set appPaginate(condition: any) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.newItemEvent.emit('Directive working')
}
}
}
Component.html:
<ng-template [appPaginate]="condition" (newItemEvent)="update($event)">
<p>{{valueFromDirective}}</p>
</ng-template>
Component.ts
import {Component, Input, OnInit} from '@angular/core';
import {Item} from "./item";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'tutorial';
condition = true;
valueFromDirective = this.title;
ngOnInit() {
}
update($event: any) {
this.valueFromDirective = $event;
}
}
Explain
Building on what @Alexander and @Zochbauer's discussion. With <ng-template>
, you can define template content that is only being rendered by Angular when you, whether directly or indirectly, specifically instruct it to do so, allowing you to have full control over how and when the content is displayed. Thus when your condition is met you will be required to use this line to display the emitted value onto the html:
this.viewContainer.createEmbeddedView(this.templateRef);
N.B. This is only to help those who think event emitter doesn't work on Angular 7+.