...

/

Customized Structural Directives

Customized Structural Directives

Let’s learn how to implement the custom structural directive.

The ability to create custom structural directives is usually handy in reducing code duplications. In many applications, we want to show or hide elements of the component’s template while adhering to some conditions. Often, these conditions are related to a business’s specific requirements, and they apply to many elements across the application.

A use case for premium accounts

As an example, we’ll focus on a particular use case in this lesson. Let’s consider an application that supports two kinds of user accounts—standard and premium. Here are the differences between these two accounts:

  • Premium users have access to everything in the application.
  • Standard users have limited access to some features.

Some features can be guarded for premium users at the route level, but some rules apply to particular elements on the page. For instance, there may be a button that performs an action that is only available to premium users. In that case, we want to hide that button from users with a standard account. First, we define the account interface, as shown below:

export interface Account {
	username: string;
  premium: boolean;
	fullName: string;
}

Then, we need a service to persist some information about the currently signed-in account. Let’s call this service AccountService, like this:

@Injectable()
export class AccountService {
	currentAccount: Account;
}

We shouldn’t worry about how the data is populated. Let’s assume that there is some other service that sets the current account so that it always has the newest data.

In the component, we can use ...