Allow Users to Configure Angular Content Directives

Isaac Mann
InstructorIsaac Mann
Share this video with your friends

Social Share Links

Send Tweet

We’re getting into Inception territory here. The user may want to override part of how the UI component Content Directives are modifying their provided UI. So, we’ll let them configure the content directives. The functionality of Content Directives is comparable to React’s Prop Getter pattern.

Instructor: [00:01] This toggler directive adds a role of switch and an aria-checked attribute based on this ON state. Now, let's say the parent component would prefer to have a role of button and an aria-pressed attribute.

[00:18] Let's configure the toggler directive to do that for us. We'll add an input decorator to this role attribute. Now if we go back to the app component, we can specify a role of button. We'll add a binding to the aria-pressed attribute and tie that to the ON state.

[00:47] Now if we inspect here, we have a role of button. If we click it, we have aria-pressed true, and click again, aria-pressed false, but you'll notice that aria-checked is also on this element, and that could confuse people.

[01:06] We need a way to override that aria-checked attribute. Let's go the toggler directive. We'll need a separate property for the aria-checked attribute. Then, we need to change the aria-checked property any time the ON property changes.

[01:27] We'll do this by registering an ON changes function. Then whenever the ON property changes, we'll set the aria-checked attribute to the new ON value. Now these changes, all these do is get us back to the original functionality.

[01:46] Now, we're going to do a little trick. We're going to make a new property called toggler, which you'll note is the same as the selector for the directive. We're going to give it a type of partial toggle directive.

[02:06] Now what this does is, says that any property on the toggler directive can be specified in here, but they don't all have to be specified. This toggler property here will be used as an override for all of these internal properties.

[02:22] We'll drop in some code to wire up these changes. For every change, the toggler override property will check each internal property of the toggler directive. If it's being overridden, then we'll set that internal property.

[02:36] We'll do this role and for aria-checked. Then if the ON state changes, we only want to update the aria-checked value, if this.toggler.aria-checked is undefined. Now, let's go back to our app component.

[02:56] We'll set the toggler value to aria-checked false. Now, let's see if that worked. We see we have a role of button and we click it ON, we have aria-pressed true, but no aria-checked. We are successfully created a configurable toggler directive.