Transfer a segment of template from one angular 4 component to another

Essentially, in the template of component 1, I have something like this:

<div>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

Then in the template of component 2 (which is a sibling of component 1), I have the following:

<div class="test">
  <h1>component 2</h1>
</div>

What I am aiming for is that when a specific variable in component 2, let's say "toggled" equals true, the template of component 2 should change to include the list from component 1.

<div class="test">
   <h1>component 2</h1>
   <ul>
     <li>1</li>
     <li>2</li>
     <li>3</li>
    <li>4</li>
   </ul>
</div>

I am working with Angular version 4.0.0 and I came across information about templateoutlet, but I couldn't quite grasp how to share it between different components. Is there a way to duplicate a template fragment from one component and use it in another component?

Answer №1

An effective way to utilize is by using the ng-template feature.

Injectable()
export class TemplatePasser{
    template;

}

Here is an example of a component that includes a template:

@Component({
  selector:'custom'
  template:`

     <ng-template #template>
         <div class="test">
          <h1>component 2</h1>
        </div>
       </ng-template>  


`
})
export class CustomComponent{

   constructor(private templatePasser:TemplatePasser){


   }
   @ViewChild('template') templateRef:TemplateRef
   ngAfterViewInit(){
       this.templatePasser.template =template;
    }
}


And here is another component that makes use of the template:

@Component({
  selector:'the-other-custom'
  template:`

   <div *ngIf="template" class="test" style="border:1px solid red">
       <div [ngTemplateOutlet]="template"></div>
       <ul>
         <li>1</li>
         <li>2</li>
         <li>3</li>
        <li>4</li>
       </ul>
    </div>  


`
})
export class CustomComponent{

   constructor(private templatePasser:TemplatePasser){}
   template
   ngAfterViewInit(){
       this.template = this.templatePasser.template;
    }
}

Check out this link for more information!

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

Tips for preventing memory leaks when utilizing the Subject programming feature

Exploring the concept of observables and subjects in JavaScript, I encountered an interesting scenario. When unsubscribing from an observable upon a click event, everything works smoothly. However, if I switch to using a Subject instead, the anonymous func ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Steps for signing up for an ngRx state

Currently, I am setting up an ngrx app to further my understanding and skills, even though the project is quite small. The project involves managing a beer inventory. Within one of the components, I aim to display a list of beers: export class BeerListC ...

What is the best way to ensure that two promises are both resolved before triggering a function from within a promise?

In my code, I have a forEach loop on a matches fetch that looks like this: matches => { matches.forEach(match => { Promise.all([this.teamService.getTeam(match._links.homeTeam.href)]) .then(team => { match. ...

Guide on how to import a CSV file into an Angular project using tensorflow.js

Having trouble uploading a CSV file from the assets folder in my Angular project using tf.data.csv. The code doesn't seem to recognize the file, resulting in an empty object being created. Can we even upload a CSV via tf.data.csv() from the assets? An ...

Delaying the tap after emitting an action in the Ngrx store

Within the realm of Ngrx store, I am currently utilizing 2 effects: @Effect({ dispatch: false }) toastSuccess$ = this.actions$ .pipe( ofType(TOAST_SUCCESS), map((action: any) => this.toastr.success(action.payload, &a ...

Is there an external class available to integrate with my interface?

Is there a method to establish an external class (part of an NPM module) as a class that adheres to a specific interface? Consider the following scenario: import {someClass} from "someNPMmodule"; interface myInterface { foo: () => void } I am now ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Expanding a TypeScript interface across different modules

For my project, I am working with Highcharts typings and encountered a need to extend certain object/interfaces it defines by adding some custom properties. Here is an example: declare namespace Chart { interface ChartOptions extends Highcharts.ChartOpt ...

Passing a boolean value from the parent Stepper component to a child step in Angular

I am facing an issue with passing the boolean value isNewProposal from a parent Angular Material stepper component to its children steps. Despite using @Input(), the boolean remains undefined in the child component, even after being assigned a value (true ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...

Communication between parents and children is crucial for building strong relationships and providing validation

This question may have been asked in a complex manner before, but I will simplify it here. In my main component, I have a form tag and Submit Button. Within this component, there is a child component that contains an input field with a required attribute, ...

cdkVirtualFor failing to display complete list of items

Having a minor issue that I can't seem to figure out the cause of. My goal is to display a list from an observable (it contains 3 objects) However, only the first two items are showing up. When I use a regular list, all three of them appear. What cou ...

What causes the failure of Angular 2 RC.6 routing when bundled with ngc + Rollup?

I have been exploring the new AOT Compiling feature in RC.6, but I have encountered a stumbling block. While I can successfully create a bundle using ngc => Rollup => Babel, I keep getting multiple warnings every time I run Rollup: The 'this&ap ...

When the Mat menu radio button inside a Bootstrap popover is clicked, it will automatically close the popover

I have a popover from Bootstrap with the autoclose attribute set to "outside" in order to close the popover when clicked outside of it. The issue I'm facing is that inside the popover, there is a material menu that opens outside of the popover. The pr ...

How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data. In my component.ts file: import { HttpClient } from "@angular/common/http"; import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/fo ...

Issue with RouterLink functionality in Angular 6

While following a Brad Traversy tutorial on coding, I implemented the instructions exactly as given. Below is my 'app.module.ts' file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/c ...

You cannot call this expression. The data type 'Boolean' does not have any callable signatures

As I delve into learning a new set of technologies, encountering new errors is inevitable. However, there is one particular type of error that keeps cropping up, making me question if I am approaching things correctly. For instance, I consistently face t ...

Is there a way to differentiate between the AzDO extension running in a YAML pipeline versus a Classic pipeline?

I've searched extensively, but haven't come across a solution yet. Does anyone have a method to determine if your extension is operating in Classic or YAML pipeline? I'm currently developing an extension that generates ANSI-colored output, ...