A specific directive I've created has the ability to display or hide an HTML element. You can view the code on StackBlitz:
<div *authorize="'A'">
This will be visible only for letter A
</div>
Here is the Authorize directive implementation:
@Directive({
selector: '[authorize]'
})
export class AuthorizeDirective implements OnInit {
letter: string;
@Input() set authorize(letter: string) {
this.letter = letter;
}
constructor(private element: ElementRef, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private authorizationService: AuthorizationService) { }
ngOnInit() {
this.authorizationService.authorize(this.letter).subscribe(x => {
x ? this.viewContainer.createEmbeddedView(this.templateRef) : this.viewContainer.clear();
});
}
}
The necessary authentication service includes the method:
export class AuthorizationService {
private notifier: Subscription;
private data$: Observable<string[]>;
constructor(private noteService: NoteService) {
this.data$ = of(['A', 'B']);
this.data$.subscribe(x => console.log(x));
this.notifier = this.noteService.get().subscribe((code: number) => {
if (code == 0) {
this.data$ = of(['C', 'D']);
this.data$.subscribe(x => console.log(x));
}
});
}
authorize(letter: string) : Observable<boolean> {
return this.data$.pipe(
map(data => data.indexOf(letter) > -1)
);
}
}
In real-life situations, the data$
would come from an API using HTTPClient.
As for the NoteService:
export class NoteService {
private subject = new Subject<number>();
send(code: number) {
this.subject.next(code);
}
clear() {
this.subject.next();
}
get(): Observable<number> {
return this.subject.asObservable();
}
}
When a note
with code 0 is emitted, it triggers an update in the data$
...
This should dynamically change the visibility of elements utilizing the directive.
In the StackBlitz example, you'll notice that by clicking a button, the div containing C should appear.
However, this functionality seems to not be working as expected. How can we trigger it successfully?