Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way:

    <div class="content-wrapper">
      <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1">
        <ng-content select="[short]"></ng-content>
      </div>

      <div class="full-wrapper" [style.opacity]="expanded ? 1 : 0">
        <ng-content select="[full]"></ng-content>
      </div>
    </div>

This allows users to switch between viewing the contracted (short) or expanded (full) version of the component.

In addition, each component features an icon. My goal is to determine whether the [short] content has been provided, and if not, substitute an enlarged version of the icon as the default contracted content for the component.

However, I am unsure how to achieve this check within the Typescript code of my component. If the [short] content is absent, I want to dynamically adjust the CSS class of the icon to transform it from a small top-left icon to a larger centered icon, occupying the space intended for the short content.

Answer №1

This approach may not be the most conventional, but it gets the job done:

To begin with, I assigned the identifier #short to the following div.

      <div class="short-wrapper" #short [style.opacity]="expanded ? 0 : 1">
        <ng-content select="[short]"></ng-content>
      </div>

Subsequently, I declared it as a ViewChild.

 @ViewChild('short', { static: true }) shortRef: ElementRef;

Lastly, within the component's ngOnInit() method, I can determine if the content within the short div is empty, indicating that the short slot has not been specified.

  ngOnInit(): void {
    if ((this.shortRef.nativeElement.innerHTML ?? '').trim() === '')
      this.useIconForShortContent = true;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The TypeScript error TS7006 is indicating that the parameter '_' is assumed to have an undefined type

In my Angular application, I have a class that implements ControlValueAccessor from the '@angular/forms' library: export abstract class CustomControl implements ControlValueAccessor { private _value: any = ''; private onChange ...

Tips for correctly decorating constructors in TypeScript

When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen? I've got some code that demonstrates the issue: First, a decorator is created which replaces the constructor of a cla ...

I'm encountering an issue with the preflight request failing the access control check. It seems to be related to not having an HTTP ok status, and I've double-checked everything to make sure I imported

I've encountered an error message stating, "Response to preflight request doesn't pass access control check: It does not have HTTP ok status." Any suggestions on what might be causing this issue? Here is the backend code snippet: app.js app.del ...

The superclass defines the type of the subclass

There is an abstract typescript class like this: abstract class Abstract { constructor (public parent?: Abstract) { } } Then, two subclasses are defined as follows: class Sub1 extends Abstract { } class Sub2 extends Abstract { } The issue aris ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Creating a parameterized default route in Angular 2

These are the routes I've set up: import {RouteDefinition} from '@angular/router-deprecated'; import {HomeComponent} from './home/home.component'; import {TodolistComponent} from './todolist/todolist.component'; import { ...

Experimenting with a file system library function using Jest and Typescript alongside a placeholder function

When attempting to test a library function that uses the fs module, I received assistance in this question on Stack Overflow. The feedback suggested avoiding mocks for better testing, an approach I agreed with @unional. I am now facing a similar challenge ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

I find myself stuck in one component in Angular routing, unable to navigate away from the current URL

After developing a function that retrieves the value of an item and redirects to a different component based on certain logic, here is the code snippet: navigate_to_page(url) { console.log(url) console.log(['../' + url]) th ...

Enhance your TypeScript code using decorators with inheritance

Exploring the realm of Typescript decorators has led me to discover their intriguing behavior when combined with class inheritance. Consider the following scenario: class A { @f() propA; } class B extends A { @f() propB; } class C exten ...

Creating a comprehensive object within a single interface using Typescript

Here is an example of an Object in TypeScript: export class test{ recordname: string; comments: [{ comment: string }] } To define it using one interface instead of multiple interfaces, you can try something like this: export int ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Leverage the power of forkJoin alongside activatedRoute

One of the observables I'm working with is the following: formData$ = forkJoin([ this.httpService.getProgramsLevelsList(), this.httpService.getProgramsTypesList(), this.httpService.getQuestionnaireReasonsList() ]).pipe( tap((res: any) => ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Issues Arise with Nativescript Layout When Content is Not in View on iOS

This problem has been giving me a hard time for the past few days. I hope someone can help me figure out what's wrong. I have a view that shows a nested list inside a main list. The main list contains header details. Everything looks fine when the in ...