14 Creating attribute directives

 

This chapter covers

  • Creating custom directives that modify a single HTML element
  • Configuring and applying custom directives
  • Receiving data in a custom directive
  • Using the directive lifecycle API
  • Generating custom events from directives
  • Creating directives that support template variables

In this chapter, I describe how custom directives can be used to supplement the functionality provided by the built-in ones of Angular. The focus of this chapter is attribute directives, which are the simplest type that can be created and that change the appearance or behavior of a single element. In chapter 14, I explain how to create structural directives, which are used to change the layout of the HTML document. Components are also a type of directive, and I explain how they work in chapter 15.

Throughout these chapters, I describe how custom directives work by re-creating the features provided by some of the built-in directives. This isn’t something you would typically do in a real project, but it provides a useful baseline against which the process can be explained. Table 14.1 puts attribute directives into context.

14.1 Preparing the example project

14.2 Creating a simple attribute directive

14.2.1 Applying a custom directive

14.3 Accessing application data in a directive

14.3.1 Reading host element attributes

14.3.2 Creating data-bound input properties

14.3.3 Responding to input property changes

14.3.4 Requiring input property values

14.4 Creating custom events

14.4.1 Binding to a custom event

14.5 Creating host element bindings

14.6 Creating a two-way binding on the host element

14.7 Exporting a directive for use in a template variable

14.8 Summary