Guide to sending a collection of templates to an Angular component

As a beginner in Angular, I've been working on creating a carousel component that can be shared. The structure of this component is based on the latest version of Bootstrap and I am looking to allow templates to be injected by the caller.

For instance, here is an example of how the carouselComponent's DOM might look:

<div class="carousel">
    <div class="carousel-indicators">
        <!-- Template passed by the caller
        <div data-index="0"></div>
        -->
    </div>
    <div class="carousel-inner">
        <!-- Template passed by the caller
        <div class="carousel-item" data-index="0"></div>
        -->
    </div>
</div>

My initial thought process looked something like this:

<carousel>
    <template-list>
        <div dataIndex="0">Ciao Mondo!</div>
        <div dataIndex="1">Hello World!</div>
        <div dataIndex="2">Hola Mundo!</div>
    </template-list>
</carousel>

In this scenario, all carousel indicators are calculated based on the template list provided, and the carousel inner section is populated with the templates from the list wrapped in div.carousel-item elements.

Unfortunately, I haven't found a solution to this problem yet. My goal is to separate the component from its logic so it can be easily reused in different scenarios.

Thank you to everyone for your assistance! :)

Answer №1

In Angular, each component is required to have a single template defined within the component.ts file.

However, it is possible to add sub-templates in the HTML file using the ngtemplate directive and switch between them as necessary.

Answer №2

If you're looking to achieve a similar effect, consider the following method:

https://codepen.io/edit/css-html-array HTML/CSS

   contentArray=[ 
            '<div data-index="0">Bonjour le monde!</div>',
            '<div data-index="1">Hallo Welt!</div>',
            '<div data-index="2">Привет мир!</div>'
            ].toString().replace(/,/g, '');

CSS/HTML

    <div [innerHTML]="contentArray"></div>

Answer №3

It's not recommended to pass HTML as input because you may need to bind data later on. It's best to handle the rendering in a child component and pass data from the parent component instead. Here's how you can create a list of objects in your parent component and then pass it as an input to your child component:

In parent.component.ts:

templateList = [
  {
    "id": 0,
    "text": "Ciao Mondo!"
  },
  {
    "id": 1,
    "text": "Hello World!"
  },
  {
    "id": 2,
    "text": "Hola Mundo!"
  }
]

And in parent.component.html:

<carousel [templateList]="templateList">
</carousel>

In carousel.component.ts:

@Input()
templateList: any[];

And in carousel.component.html:

<div class="carousel">
    <div class="carousel-indicators">
        <div *ngFor="let data of templateList" [attr.data-index]="data.id"></div>
    </div>
    <div class="carousel-inner">
        <div *ngFor="let data of templateList" class="carousel-item" [attr.data-index]="data.id">{{data.text}}</div>
    </div>
</div>

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

When running a local server with Node.js, the file index.js cannot be found if it is located one folder above the

I am relatively new to node.js and have encountered an issue while running a local server with index.js located one directory up from index.html. The browser is giving me an error message in this scenario. However, when I run the server with index.js in t ...

The CSS properties intended for ion-button elements are not taking effect

I'm attempting to set a background color when a ion-button is clicked or maintain the ion-ripple effect after it has filled the button in Ionic 4. I experimented with applying custom CSS states in global.scss, but encountered issues where the active ...

Tips for minimizing delay after user input with Material UI

Background I'm currently working on a website project that includes a carousel of MUI cards using a unique stack as the underlying component. However, I've encountered an issue where there is a noticeable 4-second delay whenever I try to scroll ...

Do not consider node_modules folder in the list of "issues"

Currently, I am executing the following task: { "taskName": "tsc watch", "command": "tsc -w", "type": "shell", "problemMatcher": "$tsc-watch" } using this specific tsconfig setup: { "compileOnSave": true, "files": ...

Angular does not require explicit closing tags in HTML

This is specified for Angular users. Answers related to Angular1 are not needed. The issue I am facing can be simplified as follows (the content is generated dynamically and can vary): <span [innerHTML]="'<p>hello there'"></span& ...

Ionic 3 Local Notification spamming a particular page with excessive pushes

Recently starting out with Ionic, I encountered an issue while developing a basic app that should display a specific page by opening a Local Notification. The problem arises when I create multiple notifications – after clicking on the second notification ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Extending a generic type with TypeScript's type constraints

I want to develop a reusable network service component that will handle CRUD requests for an "Item." For instance, if my "CatService" needs to request a list of "cats," it can utilize a "restService" instance for operations like listing, creating, updatin ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

Angular 6: Prevented Loading Resource Due to Content Security Policy: A script from self was blocked from being loaded on the page

Currently, I am developing a project in Angular 6 and everything seems to be running smoothly. Running the command ng --serve and building it using ng build results in no errors when deploying it on my local Tomcat Server. However, when attemptin ...

Angular: Dynamically add or delete an interceptor based on conditions

Is it possible to dynamically include or exclude an interceptor based on user selection? For my application, I want to enable Azure AD based SSO using the @azure/msal-angular package https://www.npmjs.com/package/@azure/msal-angular that provides an inter ...

What prevents TypeScript from automatically inferring tuple return types in RxJs streams?

When composing an observable stream, the map function infer is a union instead of a tuple. For instance: import { Component } from '@angular/core'; import { from } from 'rxjs'; import { map, tap } from 'rxjs/operators'; expo ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

Angular 2: Successfully invoking a component and receiving the parameter is a one-time deal

In my code, I have set up a route like this: { path: 'manageagreements', component: ManageagreementsComponent, children: [ { path: 'editagreement/:agreement', component: EditagreementComponent }, ] ...

Tips for modifying the export csv file name in primeng when initiating the download process

Here is a prime ng table of angular: The records are listed using the primeng table library, and you can also download csv. <p-table #dt styleClass="table table-striped" [columns]="colsCSV" [value]="reviewSSRList" selectionMode="single" [paginator]=" ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

Discriminator-based deserializer with strong typing

Seeking advice on how to effectively utilize TypeScript for strongly typing a function that operates similarly to the following example: function createDeserializer(typeDeserializers) { return (data) => { const deserializer = typeDeserializ ...

Unable to activate the 'resolve' or 'guard' functionalities on child routes within a parameterized route path in Angular 2

I have come across a similar issue to the one mentioned here, however, I haven't been able to find a solution for it especially when the URL is parameterized. There was also a related problem on GitHub which has been fixed but doesn't address my ...