Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent:

<div [my-component]="'text'"></div>

Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>).

However, for customization purposes, a user might want to include their own template within myComponent. In such cases, they would do the following:

<div [my-component]="'text'">
   <template>
   ...
   </template>
</div>

The question at hand is how can I programmatically determine if there is a <template> element within the <div> and then manipulate its content?

Answer №1

To display content conditionally based on the availability of a template in Angular, you can use the ContentChild(TemplateRef) method. This allows you to render different blocks depending on whether a template is defined or not. Below is an example showcasing this technique for Angular 2, while Angular 4 uses '*ngIf;else Block'.

  @Component({
    selector: '[my-component]',
    template: `
      my-component with input {{v}}
      <ng-container *ngIf="tpl">
        Template block:
        <ng-container [ngTemplateOutlet]="tpl"></ng-container>
      </ng-container>

      <ng-container *ngIf="!tpl">
        No Template block: <ng-content></ng-content>
      </ng-container>
    `
  })
  export class MyComponent {
    @Input('my-component') v : string;
    @ContentChild(TemplateRef) public tpl: TemplateRef;
  }
  @Component({
    selector: 'my-app',
    template: `
      <div>
        <div [my-component]="'text'">
          <template><pre>hi there</pre></template>
        </div>
        <hr>
        <div [my-component]="'text1'">
          aaa
        </div>
      </div>
    `,
  })
  export class App {
    constructor() {
    }
  }

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

Using *ngFor with trackBy for multiple properties

In my code, I am using the *ngFor directive on an array of objects that have multiple properties. I want to update this *ngFor only when specific three properties are changed. However, after reading the documentation on TrackByFunction here, I couldn&apos ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

The theming feature in Angular 5 with Bootstrap 4 and Bootswatch seems to be malfunctioning

Having trouble implementing bootswatch themes with angular 5 and bootstrap 4? I've added the following to styles.scss: @import "~bootswatch/dist/cerulean/variables"; @import "~bootstrap/scss/bootstrap"; @import "~bootswatch/dist/cerulean/ ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Access your account using Google authentication within an Angular framework

My latest project involves creating an API that allows users to log in with Google by using the endpoint http://localhost:3001/api/v1/user/google. Here's how it works: A user clicks on the link http://localhost:3001/api/v1/user/google The endpoint h ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

Angular NodeJS API failing to retrieve search data

I have implemented a search feature using Angular and Node.js. After testing it with Postman, everything seemed to be working fine. However, when I tried connecting it to the front-end Angular application, I encountered an error. Failed to load resource: t ...

Developing personalized modules in Angular version 6

I am diving into the world of Angular customization and I have a goal of developing a flexible module in Angular 6. My plan is to create this module and place it in the Node_modules folder so that it can be easily utilized by other teams within the organi ...

Prevent accidental misuse of object[index] in Typescript

It caught me off guard when I discovered that TypeScript allows the following code: interface IFoo { bar: string; } const foo: IFoo = {bar: 'bar'}; console.log( foo['anything'] // I want TypeScript to stop this ); Is there a way ...

Creating a custom validation for browsing HTML files in Angular using the Form Builder

Currently, I am using reactive form validation to validate a file upload control. I have implemented a change directive to manage its validation. <label class="btn btn-primary btn-file"> Browse <input type="file" (change)="fileChanged($event)" ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

Navigating to Angular component from Mapbox popup

I'm currently working on a mobile app with Ionic and Angular. The app features various Mapbox markers that open custom popups when clicked, each displaying unique content. I want the button within the popup to redirect users to a page with more inform ...

Missing 'id' property in ngFor loop for object type

I'm currently learning Angular and I've been following a code tutorial. However, despite matching the instructor's code, it doesn't seem to be working for me. When I try to compile the following code, I receive an error message stating ...

Setting a binary value for an angular checkbox through user input: a step-by-step guide

As a newcomer to Angular, I am currently in the process of creating a straightforward registration page by following this tutorial. The essential information I need to capture includes the user's email address, username, password, and a binary value i ...

Validating specific controls in an Angular 2 FormGroup and marking them as invalid

Currently, I have implemented an Angular 2 Reactive form using FormGroup. The main requirement is to compare the values of two fields, for which I have included a validator in the FormGroup during creation. The validation process seems to be working effect ...

Is there a way to reverse the direction of the slider's track?

Our goal in the design is for users to select a value between 0 and 20, with the selected range being that value up to 20. Currently, Angular Material slider component highlights values from 0 up to the selected value as the active track. Is there a way to ...

What is the best approach for designing a UI in Angular to showcase a matrix of m by n dimensions, and how should the JSON format

click here for a sneak peek of the image Imagine a matrix with dimensions m by n, containing names on both the left and top sides. Remember, each column and row must be labeled accordingly. ...

When a React component in TypeScript is passed as a parameter and then assigned to a variable, an error with code TS2604 may occur stating that the JSX element type does not

I am currently facing an issue with handling props of a passed React Element in my Factory. I am getting a TypeScript error that says: TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures. This is my Child co ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...