DEV Community

Yevheniia
Yevheniia

Posted on

Using ng-content in Angular. Simple DropDownComponent.

Image description

ng-content

Is a directive that allows content projection, enabling us to insert and display content within a component's template from its parent component.

When it might be useful?

Let’s imagine that we have the drop-down component. We reuse this component in a many different places within our app.The drop-down itself always looks the same, only the options inside are changing. The design of the menu always is the same.

Image description
Image description

But the trigger of that dropdown might have a few different views.

View number 1:

Image description

View number 2:

Image description

View number 3:

Image description

How many ways do we have to implement it?
Solution number 1: add an @Input() decorator to with a type of trigger view and use it’s value as an *if-expression inside HTML.

Solution number 2: add an @Input() same as in the previous one and use its value for *ngSwitch with the several possible *cases inside HTML.

Solution number 3: no extra @Input() decorator inside , no extra expressions inside HTML, we going to use ng-content.

For sure those ways are only part of all possible ones, there are certainly others, it’s just 3 of the fastest ones from my point of view:) If you usually use another one feel free to share it in the comments.

In this article, I’m going to show you how to create the simple drop-down component with differrent views of it’s trigger using ng-content.

DropDownComponent.html
<div class="drop-down-component">
    <div #dropDownMenuTrigger (click)="openDropDown()" class="drop-down-component__trigger">
        <ng-content select="[drop-down-trigger]"></ng-content>
    </div>
    <ul class="drop-down__list">
        <li *ngFor="let option of dropDownData" class="drop-down-component__option">
            <a (click)="selectOption(option)" class="drop-down-component__option-name" role="button">
                {{ option.name }}

            </a>

        </li>
    </ul>
</div>


DropDownComponent.ts
  public isDropDownVisible: boolean = false;

 @Input() dropDownData: ITDropDown[] | null = null;
 @ViewChild('dropDownMenuTrigger', { read: ElementRef, static: false })
    dropDownMenuTrigger: ElementRef;

 public openDropDown(): void {
  this.isDropDownVisible = !this.isDropDownVisible;
}

public selectOption(option: ITDropDown): void {
  //your logic here
}


ParentComponent.html
<app-drop-down [dropDownData]="dropDownData">
    <div drop-down-trigger>
        <img src="/assets/images/your-icon-name.svg" class="drop-down-component__trigger-inner" />
    </div>
</app-drop-down>
Enter fullscreen mode Exit fullscreen mode

As you can see it is a really simple way to create a dynamic view of a drop-downs trigger that frees us from the need to use extra expressions and decorators.

Top comments (0)