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

What is the process for setting a Type to a prop in React?

I have a main component: // DashboardComponent.tsx const DashboardComponent = () => { const {loading, error, data} = useQuery(resolvers.ReturnAllMovies); if (loading) return <p>loading</p>; if (error) return <p>Error! ${error.m ...

Angular 2: Musing on the potential of Hot Module Replacement and the power of @ngrx/store

If you're just getting started, this link might be helpful: understanding the purpose of HMR. When it comes to managing and designing large projects, I'm still in the early stages and haven't grown a wise beard yet. So, I'm seeking adv ...

The functionality of data binding becomes unclear when the ngif directive is applied to a mat-selection-list in

I am facing an issue with displaying a mat-selection-list based on a condition. Since adding the ngif condition, the data is consistently being set to undefined. I am struggling to identify the root cause of this problem. Thank you in advance for your assi ...

Angular templates do not support text interpolation within ng-template tags

I'm attempting to insert a URL address inside my ng-template using text interpolation, but it's not functioning as expected. Here is the HTML code snippet: <ng-template #div2> <iframe width="560" height="315" src="{{video ...

What steps do I need to take to successfully integrate Firebase authentication with Angular2 FINAL?

After upgrading to Angular2 Final, I completed the migration project steps to transition everything over. Surprisingly, there were no errors during authentication; however, the issue arises post-authentication. Upon redirection back to the page, the authen ...

The NestJS HttpService is encountering issues with API calls when an Interceptor is implemented

When using NestJS API App with HttpService to call another API, the functionality works successfully without any custom interceptors. However, the issue arises when attempting to view the response from the called API. The following code snippet showcases ...

What steps do I need to take to enable the about page functionality in the angular seed advance project?

After carefully following the instructions provided on this page https://github.com/NathanWalker/angular-seed-advanced#how-to-start, I successfully installed and ran everything. When running npm start, the index page loads with 'Loading...' I ha ...

Navigating with the InAppBrowser in Ionic Angular after a POST request

Currently, I am in the process of redirecting my app to 3DS for a payment method. According to the documentation, the steps involved are: Obtain the action.url and the action.method from the /payments response. Redirect the shopper to the specified URL us ...

The significance of Import and Export in the Initialization of Angular's NgModule

I recently completed the Angular Tour Of Heroes tutorial and reached the router section. I came across this code snippet in the app-routing.module.ts file that left me puzzled: app-routing.module.ts file: @NgModule({ //Exporting the routermodule allo ...

Utilize personalized Bootstrap variables within your Angular application

I am attempting to customize the default colors of Bootstrap within my Angular project. I have established a _variables.scss file in the src directory. Within this file, I have included the following code: $primary: purple; Next, I imported my _variables ...

What is the best way to transfer the $event parameter from a dynamically generated function that requires the $event argument during a typical mouse click operation?

On an angular HTML template, I have a click handler that passes the $event argument to the handler function. My goal is to call this function programmatically on ngOnInit to initialize the component with default data as if the button had been clicked: Bel ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

Combining tuples with their corresponding data types

Trying to define a new type: type Union = [1, "one"] | [1, "first"] | [2, "two"] type GetTuple<T, U> = Extract<T, [U, ...unknown[]]>; type ObjectFromUnion<T extends Union[0] = Union[0]> = { number: T, word: ?? } Looking to utiliz ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

Middleware in Redux Toolkit is ineffective in managing successful asynchronous actions

After integrating my own middleware into the Redux-Toolkit store using configureStore in my Next.js app, I noticed that the middleware functions appear to be greyed out. I added them via: getDefaultMiddleware({ thunk: { extraArgument: updateNavTabMid ...

Angular 7 - Creating tooltips with multiline text

I've utilized template strings to create a multi-line string. toolTip = ` ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number}}`; The issue I'm facing is that w ...

Determine the `overall` amount and adjust `overall` to equal `quantity * price` within a Typescript

I am looking to perform a calculation similar to this: total = quantity * price and continuously update the total when either the quantity or the price changes. template-output-snapshot app.component.html <form [formGroup]="editform" (ngSubm ...

Creating a unified observable by merging various iterations in RXJS

For a while now, I've been grappling with the challenge of combining multiple asynchronous calls. Every time I think I'm close to figuring it out, I hit a roadblock at a foreach loop that I just can't seem to crack. Currently, my approach i ...