Single Component Tabs in Angular - Simplify your tab implementation with just one

As a newcomer to angular, I am trying to create tabs. I came across an intriguing example, but I am struggling to incorporate everything into the same component without using the tab component template.

Is there a way to transfer all the content from the tab component to the app component?

DEMO

I would like to move the code (tab component) to the app component and transfer all the HTML code in the template to app.component.html. Could this be done successfully?

Appreciate your help.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'tabs',
  template: `
    <mat-tab-group>
      <ng-container *ngFor="let tab of tabsName">
        <mat-tab label="{{ tab.name }}">
          <ng-container [ngTemplateOutlet]='tab.template'></ng-container>
        </mat-tab>
      </ng-container>
    </mat-tab-group>
    <ng-content></ng-content>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class TabComponent  {
  @Input() tabsName: any;

  onSelect(event){
    console.log(this.tabsName[0].name)
  }
}

Answer №1

To transfer the complete content to the app component, you can do so by substituting the input variable with a local variable.

Here is the template for the App component:

<mat-tab-group>
  <ng-container *ngFor="let tab of allTabs">
    <mat-tab label="{{ tab.name }}">
      <ng-container [ngTemplateOutlet]='tab.template'></ng-container>
    </mat-tab>
  </ng-container>
</mat-tab-group>
<ng-content></ng-content>

<ng-template #Shop>
  <form>
    name: <input type="text">
  </form>
</ng-template>
<ng-template #Notification>
  <h1>list of notification</h1>
</ng-template>
<ng-template #Review>
  <h1>list of review</h1>
</ng-template>

I have edited your Stackblitz example by removing the tab component.

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 using Tailwind, be aware that the @screen directive does not automatically generate media queries in

Angular 12 & tailwind ^3.0.12 No media queries are being generated on the screen after compilation based on breakpoints. section { @apply w-full px-6 py-24; @screen sm { @apply py-14; } @screen md { @apply px-0 py-20 max-w-5xl mx-auto; ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Display or conceal list elements using Angular directives in the HTML

I currently have a lineup of 4 items, with the initial 2 visible and the latter half hidden. There's also a button labeled "expand / collapse" that alters the visibility of the final 2 items. <ul> <li>Item 1</li> <li>Item 2 ...

Searching for a regular expression pattern that can identify a match when a colon is present within both sets of double curly brackets

I want to optimize the method below by using regex instead of indexOf: hasMatch(value: any): boolean { if (isDefined(value)) { const valueStr = JSON.stringify(value); return valueStr.indexOf('{{') > -1 && valueStr.index ...

What causes the dispatch property to be undefined in a connected wrapped component within a connected Higher Order Component while using react-redux in conjunction with typescript?

As a new user, I am facing a particular challenge. I am working with a Higher Order Component (HoC) that injects properties into a wrapped component. The HoC itself returns a React.ComponentClass that is connected to the redux store with mapped and dispatc ...

Adding sass files to Angular 4 using Webpack 2

I am currently working on integrating scss files with my components in an Angular 4.3.5 web application using webpack 2.2.1, as I am unable to utilize angular-cli at this time. Below is the section of my webpack.config file that pertains to the loaders: ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

Different types require individual declarations for their private properties

While immersing myself in learning Angular, a TypeScript-based framework, I encountered an intriguing error: The class 'SnackbarService' is mistakenly extending the base class 'MatSnackBar'. There are separate declarations for types of ...

Sign up for Observable and receive notifications for specific events

I am working with an Angular service that looks like this: export class EventService { private subject = new Subject<Event>(); send(code: EventCode, data?: any) { this.subject.next(event); } clear() { this.subject.next(); } g ...

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

Introducing a detailed model showcasing information sourced from an array of objects within Angular 14

I'm struggling to showcase detailed models for various elements in my project. In essence, I have a collection of cards that hold diverse information data. The objective is simple: upon clicking a button to reveal more details about a selected card, a ...

"What are the benefits of utilizing Dependency Injection tokens within Angular 4 and when is the ideal time to implement

I have been exploring the concept of using InjectionToken for injecting environment variables (plain objects) into a service. I find myself puzzled as to the reasons and methods for incorporating tokens in Dependency Injection. Despite my efforts to resear ...

Switch the dropdown icon in ng-bootstrap when clicked

Click me to switch icon from fa-angle-up to fa-angle-down. Initially displaying the fa-angle-up icon, clicking it will change it to fa-angle-down. <div class="col text-right"> <div ngbDropdown placement="top-right" class="d-inline-block"> ...

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

Nextjs build: The specified property is not found in the type 'PrismaClient'

I have a NextJS app (TypeScript) using Prisma on Netlify. Recently, I introduced a new model named Trade in the Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continu ...

Error: Attempting to access the 'tokenType' property of an undefined object is not allowed

We encountered an error while attempting to embed a report using the Power BI Angular library. TypeError: Cannot read properties of undefined (reading 'tokenType') at isSaaSEmbedWithAADToken (reportEmbed?navContentPaneEnabled=false&uid=am ...

Authentication dependencies in Angular Services (Version 17)

Within my angular application, I have successfully integrated user authentication alongside a recipe library that is specific to each individual user's account. To achieve this functionality, I've employed an AuthService and a RecipeService. Howe ...

Angular and Ngrx: The optimal approach for choosing a value within a component and a function

While browsing through this Stack Overflow thread, I stumbled upon a question similar to mine. However, I'm curious if the solution provided in the comments is still considered the best practice in today's standards. Here's where I stand: ...