Ole Ersoy

Image by Jevgeni Fil from Pixabay

Scenario

We have the code console.log("Hola!") .

Is this an expression or a statement?

Approach

An expression returns a value. The statement console.log("Hola!") does not return a value so it is not an expression.

The below code illustrates an expression.

const greeting = spanish ? "Hola!" : "Hi!";

If spanish is true greeting is assigned Hola! otherwise Hi! is assigned.

The expression part of the statement is spanish ? “Hola!” : “Hi!” .

Demo

--

--

Image by Ulrike Leone from Pixabay

Scenario

We have a header within a flex container that we want to expand as space allows and also to have a minimum width of 200px.

<div style="display: flex">
<div id="header">this is the header</div>
</div>

Approach

Style the header div with flex: 1 0 200px; , which means flex-grow: 1 and so it will expand to fill space and flex-shrink: 0 , which turns shrinking off after the item reaches the minimum size of 200px;

Demo

--

--

Image by Peter Dargatz from Pixabay

Scenario

If the *isReady directive is is set to false , then we want to render a SpinnerComponent , otherwise we want to show the content contained within the element that the directive is declared on.

<h1><code>isReady</code> set to <code>true</code></h1>
<div *isReady="true">Content</div>
<h1><code>isReady</code> set to <code>false</code></h1>
<div *isReady="false">
<span>Display the spinner…

--

--

Image by Martin Str from Pixabay

Scenario

We wish to display an elements content only after after some application state is ready.

<h1><code>isReady</code> set to <code>true</code></h1>
<div>
<p *isReady="true">Content</p>
</div>
<h1><code>isReady</code> set to <code>false</code></h1>
<div >
<p *isReady="false">Content</p>
</div>

We could have easily done this with *ngIf , but this approach can be adapted to more specific use cases, such as only displaying content when a certain language is being rendered.

Approach

We will create the directive like this.

Note that the content contained within the element that the directive is attached to is passed in via the constructor TemplateRef<void> argument.

If the directive is truthy we insert the content with the ViewContainerRef.createEmbeddedView call.

if (this.isReady) {
this.vcr.createEmbeddedView(this.templateRef);
}

Demo

--

--