The directive [ngTemplateOutet] is functioning properly, however, the directive *ngTemplateOutlet is not functioning as expected

I have been struggling to create a component using ngTemplateOutlet to select an ng-template, but for some reason *ngTemplateOutlet is not working in this case (although [ngTemplateOutlet] is functioning correctly).

Below is the code I am currently using:

demo-frame.component.html:

<div class="frame-wrapper">
  <ng-container [ngTemplateOutlet]="(windowWidth < 480)? this.realView : this.shelledView">
    <ng-template #realView>
      realView work!!
    </ng-template>
    <ng-template #shelledView>
      shelledView work!!
    </ng-template>
  </ng-container>
</div>

demo-frame.component.ts:

import { Component, OnInit, ViewChild, TemplateRef, HostListener} from '@angular/core';

@Component({
  selector: 'app-demo-frame',
  templateUrl: './demo-frame.component.html',
  styleUrls: ['./demo-frame.component.scss']
})
export class DemoFrameComponent implements OnInit {

  public windowWidth : number;
  @ViewChild('realView') realView : TemplateRef<any>;
  @ViewChild('shelledView') shelledView : TemplateRef<any>;

  constructor() { }

  getWindowWidth(){
    this.windowWidth = window.innerWidth;
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.getWindowWidth();
  }

  ngOnInit() {
    this.getWindowWidth();
  }

}

As a beginner in Angular, I would appreciate if someone could help me identify where I am going wrong.

Answer №1

In Angular, when a directive starts with an (*) asterisk prefix, it indicates that it is a structural directive. Basically, Angular will wrap your host element inside an ng-template behind the scenes. So in your scenario, the entire ng-container will be wrapped inside an ng-template as shown in the code snippet below. This explains why viewChild was not initialized in your code and therefore not working properly.

<div class="frame-wrapper">
  <ng-template [ngTemplateOutlet]="(windowWidth < 480)? this.realView : this.shelledView">
    <ng-container>
    <ng-template #realView>
      realView work!!
    </ng-template>
    <ng-template #shelledView>
      shelledView work!!
    </ng-template>
  </ng-container>
  </ng-template>
</div>

For more information, check out this resource

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

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

I'm uncertain about the appropriate RabbitMQ subscription endpoint with STOMP

I'm using spring-boot-starter-amqp library to send messages to RabbitMQ. I've configured the exchange as spring-boot-exchange and set the routing key as group.n (where n is variable). I'm trying to retrieve these messages in Angular using n ...

Unable to associate Interface with HTTP response

When I run the following code in Chrome console, I get an error: ERROR TypeError: t.json(...).map is not a function. However, both ng serve -prod and ng test --sm=false work fine. My goal is to map the result to the model in Interface and display it in HT ...

Error in Angular 2: Uncaught Promise TypeError - Unable to access property 'title' of undefined

Whenever I attempt to include a text input field with dual binding in my App, the following error pops up: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined TypeError: Cannot read property 'title&ap ...

Processing a list in Angular using Observables

In my Angular12 application, I am fetching data from a Firebase Realtime DB using AngularFire. To streamline my code and ensure consistency, I have implemented a DAO service to preprocess the retrieved data (e.g., converting string dates to Date objects). ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...

Display the nb-datepicker component within the ng-sidebar container

I am facing a challenge with displaying nb-datepicker in ng-sidebar on an Angular 6 based web portal. The issue stems from the fact that I am unable to modify the CSS of ng-sidebar, which has a default z-index of 99999999. This causes the popup for the dat ...

Issue with Angular 6 Animation not showing up

Looking to incorporate an animation spinner into my Angular app Found this spinner example: https://codepen.io/z-/pen/OPzNLz spinner.component.html import { Component, OnInit } from '@angular/core'; @Component({ selecto ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Combine two arrays of data sources

mergeThreads() { const userId = this.auth.getUser().uid; const buyerThreads$ = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges(); const sellerThreads$ = this.afs.collection ...

The MongoDB connection in NextJS 14 is causing a delay in loading the page

Occasionally, when trying to open a page through the dashboard menu, nothing happens on the frontend. There's no loading screen or any indication that the page is being loaded. How can this problem be prevented so that the page loads as intended? This ...

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...

Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators. Here is our old code snippet: const ADD_NAME = 'ADD_NAME'; /** * Se ...

What is preventing me from installing Angular Bootstrap?

Version Information: Angular CLI: 14.2.3 Node: 16.15.1 Package Manager: npm 8.12.1 Operating System: darwin x64 Encountered an error while trying to install Angular Bootstrap using NPM: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! ...

How can I assign a type to an array object by utilizing both the 'Pick' and '&' keywords simultaneously in TypeScript?

As a beginner in TypeScript, I am looking to declare a type for an array object similar to the example below. const temp = [{ id: 0, // number follower_id: 0, // number followee_id: 0, // number created_at: '', // string delete_at: &ap ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

FIXED-IONIC 3: The 'questions' property is missing from the 'Object' type

Encountering an issue with a single line of code and exhausted all resources in attempts to resolve it. Seeking assistance for my simple quiz, disregarding the current data presentation. The trouble arises within my data.ts file, specifically at one parti ...

retrieving class instances from a Firebase database

I have a new group called GroupA group A { value1: string; value2: string; total(): number { return value1 + value2; } } I want to store instances of GroupA in my database, but when I retrieve them, they are in Object format which does not a ...

Is there a way to identify and retrieve both the initial and final elements in React?

Having an issue with logging in and need to retrieve the first and last element: Below is my array of objects: 0: pointAmountMax: 99999 pointAmountMin: 1075 rateCode: ['INAINOW'] roomPoolCode: "ZZAO" [[Prototype]]: Object 1: pointAmoun ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...