Our NGB collapse component template

Create another file within the ngb-collapse directory, name it ngb-collapse.component.ts, and add the following code in it:

<p> 
<button type="button" class="btn btn-outline-primary" (click)="isCollapsed = !isCollapsed">
{{ isCollapsed ? 'Show' : 'Hide' }} Instructions
</button>
</p>
<div id="collapseExample" [ngbCollapse]="isCollapsed">
<div class="card">
<div class="card-body">
These are the hypothetical instructions for something.
</div>
</div>
</div>

Let's look at this code together. The first thing of interest to us is the binding of the click event to the expression, which basically toggles our isCollapsed variable, defined in our component class, between true and false:

(click)="isCollapsed = !isCollapsed" 

The text for our toggle button is always set to one of two values. When the instructions are displayed, the button text reads Hide Instructions. When the instructions are hidden, the button text reads Show Instructions. This is, of course, the behavior we want, but at first glance, you may assume that it takes an if .. else construct to make it all work. Surprisingly, thanks to Angular's interpolation template syntax, it only takes a tiny amount of code to alter the button's text depending on the value of our isCollapsed variable. Let's take a moment to see the tiny code snippet responsible for determining what the button text should be, and how it renders it for us:

{{ isCollapsed ? 'Show' : 'Hide' }} Instructions

In Chapter 7, Templates, Directives, and Pipes, we took a look at all the symbols that we can use in our template syntax—such as interpolation, two-way binding, and so on. The symbol that works its magic for us, in this case, is the interpolation symbol (that is, the set of double curly braces). The reason I call it magical is that not only does it serve as a string interpolation, but it is also smart enough to handle expressions and even function calls. So, we're not restricted to just having a variable name being treated as a simple string interpolation. 

To determine what our button text should be, we use JavaScript's ternary operator syntax to render (or interpolate) the text to one of two values, Show or Hide, based on the value of our isCollapsed variable. Of course, whatever the Boolean value is, the Instructions text will always be rendered, resulting in the button text being either Show Instructions, or Hide Instructions. This is all done succinctly, and inline. Pretty cool, isn't it?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.96