Solution: Customized Structural Directives
Here’s the solution to the task with the expected result and explanation.
We'll cover the following...
Solution
Here’s a possible solution for the given task:
import { Directive, OnInit, EventEmitter, HostListener, Input, Output, TemplateRef, ViewContainerRef } from '@angular/core'; import { AccountService } from '../services/account.service'; @Directive({ selector: '[appForRoleOnly]' }) export class ForRoleOnlyDirective implements OnInit { @Input('appForRoleOnly') role!: 'premium' | 'standard'; constructor( private accountService: AccountService, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef, ) { } ngOnInit() { // Get the account from the service const account = this.accountService.currentAccount; // Calculate if it should render or not for the account type const showForPremium = account.premium && this.role === 'premium'; const showForStandard = !account.premium && this.role === 'standard'; if (showForPremium || showForStandard) { // Render the view this.viewContainerRef.createEmbeddedView(this.templateRef); } else { // Clear the view this.viewContainerRef.clear(); } } }
The task's solution
Solution explained
To solve this exercise, we need to get information about the required role for this instance of the directive. We can obtain ...