What is the method for retrieving a child element from a TemplateRef variable?

I'm currently working with a component that has a modal feature. The modal is enclosed within an <ng-template> element.

<ng-template #modalm let-modal>
...
   <button type="button" (click)="onSubmit()" class="btn btn-primary">OK</button>
...
</ng-template>

With this setup, I have the ability to open and close the modal directly from my component.ts file.

constructor(private modalService: NgbModal,
    private activeModal: NgbActiveModal)
...
public openModal(modalm: TemplateRef<any>){
    this.activeModal = this.modalService.open(modalm);    
    const btn = modalm.elementRef.nativeElement.querySelector('.btn-primary');
  }

Now, I am trying to access the button element within the modal and set a property on it. I tried using the solution provided in the response of How do I find Element inside TemplateRef, which involves calling querySelector on modalm.elementRef.nativeElement. However, I encountered an error:

TypeError: modalm.elementRef.nativeElement.querySelector is not a function

I'm puzzled as to why I am unable to execute querySelector in this scenario.

I am aware that I need to use the TemplateRef type because of the ng-template wrapping. Can someone guide me on the correct syntax for accessing an element within the modal?

Answer №1

Watching a tutorial by Max NgWizard led me to the solution I was looking for. I was trying to access the DOM in a TemplateRef instance to set a button property in my TypeScript file, but couldn't find a way to do so. The comments mentioned that setting element properties in a ts file is not recommended, and it's better to use directives like ngClass in the HTML markup and control it through a flag in the ts file. I created a class in the component css file for this purpose.

First, I created a class ".myClass" with the necessary style properties. Then, I added a conditional directive to my button to apply this class, like

<button type="button" (click)="onSubmit()" class="btn btn-primary" [class.myClass]="loadComplete">OK</button>

The boolean loadComplete determines when the css class should be applied from the ts file.

To ensure that my custom styles take precedence over Bootstrap styles, I had to use the !important statement for each property in the css class.

.myClass {
    outline: none;
    border: none !important;
    -webkit-box-shadow: none !important;
    -moz-box-shadow: none !important;
    box-shadow: none !important;
    color: red !important;
  }

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

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Encountering the message "npm ERR! missing script: start" following the update to .Net 3.0

Previously, the ASP.Net Core 2.2 code (upgraded from 2.1) did not include a start script in package.json. https://github.com/TrilonIO/aspnetcore-angular-universal/blob/master/package.json Upon upgrading to ASP.Net Core 3.0, it now requires a start script ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Error encountered: Imagemagick throwing a typeerror due to the inability to parse properties of undefined while trying to read 'convert

I'm currently working on developing a pdf conversion feature for my nestjs project. Unfortunately, I've encountered an error that reads as follows: TypeError: Cannot read properties of undefined (reading 'convert') I am pretty confiden ...

Dynamically altering the CSS4 variables in real time

I am facing the challenge of managing multiple CSS4 variables, including primary, for various companies. How can I dynamically change the primary CSS4 variable color based on the company? Note: My specific requirement is to update the primary variable glo ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

Challenges with promises in Angular Firebase Realtime DB

Having some difficulties with Angular and Firebase Realtime DB. In my database service, I created a function like this: getAllProject() { return firebase.database().ref('project').once('value').then((snapshot) => { if (snapsh ...

Encountering an error while receiving a response for the Update API request

Recently, I ventured into the world of swagger and decided to test it out with a small demo project in node-js. I successfully created 5 APIs, but encountered an issue specifically with the PUT API. Surprisingly, when testing it on Postman, everything work ...

The presence of a constructor in a component disrupts the connection between React and Redux in

I am facing an issue with the connect function from 'react-redux' in my Typescript class example. The error occurs at the last line and I'm struggling to understand why it's happening. The constructor is necessary for other parts of the ...

Experience the enhanced features of Joomla 4 with a unique horizontal menu spanning across 2 rows

Currently, I am working with Joomla 4 using a customized Cassiopeia theme as the child theme. My goal is to display the menu items across two horizontal rows instead of one. However, whenever I add an item to the menu, it causes the navigation container to ...

Stop SCSS from processing CSS variables in Angular-CLI

I am currently using Angular5 with sass v1.3.2. My goal is to dynamically change a color that is widely used in the scss files of my single page app without having to recompile new files. This color is globally defined in my _variables.css as: $brand: # ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

What are the steps for deploying an Angular 2 project to a server with PUTTY?

After developing an Angular 2 app with Angular-CLI on my local server, I have reached the production phase and now need to upload it to a CentOS server using Putty. I attempted to follow instructions from this source for installing node and npm on the ser ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

Is it possible to dynamically insert additional fields when a button is clicked?

My FormGroup is shown below: this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], desc: ['', Validators.maxLength(3000)], category: ['', Validators.require ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Incorporating node packages into your typescript projects

I have been exploring various discussions on this forum but I am still unable to make it work. My goal is to compile the following code in TypeScript. The code is sourced from a single JavaScript file, however, due to issues with module inclusion, I am foc ...