Angular4 Blueprint

Here is a simple demonstration of ngTemplate that I have coded:

<div> <ng-container [ngTemplateOutlet] ="template1"> </ng-container></div>

Below are the template examples:

<ng-template #template1> This is the 1st template </ng-template>
<ng-template #template2> This is the 2nd template </ng-template>

While everything is working as expected, I am encountering an issue trying to pass dynamic values to [ngTemplateOutlet].

The desired functionality is something like this:

<div> <ng-container [ngTemplateOutlet] ="selectTemplate"></ng-container> </div>

Where either template1 or template2 can be selected.

However, upon passing a dynamic value defined in my TypeScript file, an error occurs:


ERROR TypeError: templateRef.createEmbeddedView is not a function

The TypeScript code responsible for setting the dynamic value is as follows:

if(some condition) {
     this.selectTemplate = "template1";
} else {
     this.selectTemplate = "template2";
}

Answer №1

Your initial example shows that you are assigning the ngTemplateOutlet to the value of the template1 expression, which corresponds to the first ngTemplate element.

In contrast, in your second example, you are binding the ngTemplateOutlet to the selectTemplate expression, which is not a template element - it has been defined as a string!

To resolve this issue, you need to declare the template references within your component using the ViewChild decorator:

@ViewChild('template1') template1;
@ViewChild('template2') template2;

Afterwards, ensure that selectTemplate references the actual element rather than just its name:

if (some condition) {
     this.selectTemplate = this.template1;
}
else {
     this.selectTemplate = this.template2;
}

Remember that the ViewChild variables may not be initialized until the component's view is ready - consider utilizing the ngViewAfterInit hook to handle this waiting period.

Answer №2

Angular 5 Update

ngOutletContext has been rebranded as ngTemplateOutletContext

For more information, visit https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

Initial Version

You are able to provide a context

<ng-container [ngTemplateOutlet]="template1; context: {foo: 'foo', bar: 'bar', $implicit: 'implit' }"

In the template, you can utilize it like this

<ng-template #template1 let-foo1="foo" let-foo2="bar" let-item>
  This is the first template
  <div>foo1: {{foo1}}</div> 
  <div>foo2: {{foo2}}</div>      
  <div>item: {{item}}</div>    
 </ng-template>

I hope the naming convention I used is clear and not too confusing. I have tried to differentiate between

  • the name when passing the value to the context
  • the name as it is utilized within the template
  • $implicit which doesn't necessitate ="somename" in the template variable definition (let-item)

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 mechanism behind callbacks in AngularJS when making a call to a REST service?

Currently, I am diving into the world of AngularJS and REST. The code snippet that I'm analyzing has the term callback repeatedly used in an authentication function. I'm curious to know if "callback" is a JavaScript or Angular keyword, or simply ...

Exporting keys of objects one by one

I am trying to mock the `fs` module in vitest using [memfs](https://github.com/streamich/memfs). To do this, I have created a mock file located at `./__mocks__/fs.ts` where I have set up the mocked volume and fs. However, I am facing an issue with the moc ...

Issues have been reported with Angular 10's router and anchorScrolling feature when used within a div that is positioned absolutely and has overflow set

I feel like I may be doing something incorrectly, but I can't quite pinpoint the issue. Any help or pointers would be greatly appreciated. My current setup involves Angular 10 and I have activated anchorScrolling in the app-routing.module file. const ...

Unlocking the Power of Rendering DOM Elements with Protractor

Recently, I began learning protractor and encountered some difficulties extracting text from a DOM object. Here is a snippet of code from an AngularJS application: "<div class="input-group application-item-field"> <input type="te ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

Shut down the Pub/Sub client following a transmission via socket.io-mongodb-emitter

I am facing an issue with emitting a message into a socket.io room using socket.io-mongodb-emitter. The problem lies in the fact that my script never exits as it maintains a connection to mongodb. Take a look at the examples below and provide some suggest ...

Can Angular Material Tabs be customized to have a different style?

I need help styling my mat-tabs to achieve a specific look. Here is the design I am trying to replicate: https://i.stack.imgur.com/tg6XC.png https://i.stack.imgur.com/tth0z.png However, I'm encountering an issue where the white border under the curr ...

The "else" statement is never being executed

Trying to create a form where users enter their first name, last name, and city. If any input is empty or contains numbers, a message should appear requesting to fill out all boxes without numbers. Otherwise, display a personalized quote using the input in ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

Are there varying levels of efficiency when retrieving elements by ID versus by class using JavaScript/jQuery?

When it comes to JavaScript/jQuery, is there a performance disparity between locating elements by id versus by class? Is one method superior over the other? Could it be attributed to ID or Class indexes being generated in the DOM? Ultimately, does the di ...

Ways to showcase a variable's value in conjunction with text using .html() method

Hello, I need assistance with printing a value in a popup window. Below is the code I am using: "code" $('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11); https://i.s ...

Only trigger NgRx actions when specific properties change during Rxjs Polling

I am working with a Rxjs Polling effect that looks like this: updateProductData$ = createEffect(() => this.actions$.pipe( ofType(fromActions.loadProduct), switchMap(_) => this.http.get('endpoint').pipe( delay(1000), ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Steps to resolve UnhandledPromiseRejectionWarning in discord.js v12 when encountering TypeError: Cannot read property 'get' of undefined

Trying to run a nuke command, but encountering an error when executing ($nuke): (node:3888) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined Below is the main.js code for the nuke command: const args = message ...

Tips for updating an object with a narrowed type property in TypeScript

Is it possible to conditionally narrow the type of object properties without causing an error when reassigning the whole object to another variable? type A = { prop: string | number; } type B = { prop: string; } function f(a: A) { if (typeof a.pro ...

How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false: function submitValidate() { var xmlhttp; xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari try { xmlhttp ...

Activate backdrop feature in offcanvas mode

When trying to open an offcanvas panel, I discovered that adding show to its class is necessary for it to open. However, this caused the backdrop feature to stop working, and now clicking outside the panel does not close it. Is there a way to achieve the p ...

Chrome experiences locking issues with jQuery ajax when using JS for and while loops

A close friend of mine has a specific requirement to gradually transfer data from one database to another while monitoring any errors that occur in the process. To assist him, I took it upon myself to create a script swiftly, completing it within an hour. ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...