Search⌘ K
AI Features

Solution: Customized Structural Directives

Explore how to implement custom Angular structural directives that conditionally render content based on user roles. Learn to use Input properties and manipulate the view container to show or hide elements dynamically, improving your app's user access control and code clarity.

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 ...