Adjusting the width of a nested Angular custom directive within an *ngIf statement to an absolute value

I'm struggling with a custom angular directive that I only want to display conditionally using ng-if. The directive contains HTML elements, one of which is positioned absolutely.

My goal is to make the absolute element's width match the root width of the directive. However, I am unable to change the display of the directive's root to relative.

How do you suggest I go about accomplishing this task?

UPDATE: To clarify, here is a jsfiddle link - http://jsbin.com/qofolahani/edit?html,css,js,console,output

Keep in mind that in the link function, I have not set the css styling for the element so the width remains at 0, preventing me from adjusting the child div's width accordingly.

Answer №1

The problem lies in your usage of restrict: E.
Browsers do not bind the getCalculatedStyle method to non-standard DOM entities.

To fix this, change the directive to be used as an attribute:

<div my-dir></div>

Implement the directive like so:

{
    restrict: 'A',
    link : function (scope, element) {
      element.addClass('my-dir');
      element.find('.my-dir-content').width(element.width());
    },
    template: '<div class="my-dir-content"></div>'
}

Alternatively, you can use internal templated divs only.
Setting replace: false can assist with this.

{
  restrict: 'E',
  link : function (scope, element) {
    var o = element.find('.my-dir');
    var i = o.find('.my-dir-content');
    i.width(o.width());
  },
  replace: false,
  template: '<div class="my-dir"><div class="my-dir-content"></div>/div>'
}

Another option is to replace the parent node:

{
  restrict: 'E',
  link : function (scope, element) {
    var i = element.find('.my-dir-content');
    i.width(element.width());
  },
  replace: true,
  template: '<div class="my-dir"><div class="my-dir-content"></div>/div>'
}

JSBin Preview


Bonus Tip:
To update the width on window resize, include this piece of code:

$(window).on('resize', onResize);
function onResize() {
  i.width(o.width());
}
scope.$on('$destroy', function(){
  $(window).off('resize', onResize);
});

Answer №2

To apply a css style to the main element of the directive, you should define its position as relative. This can be done with the following code:

custom-directive {
   position: relative;
}

By setting the root html element to position: relative, it allows the inner html elements to be positioned absolutely in relation to the directive.

Next, you can target the inner html element and specify the following styles:

inner-html-element {
    position: absolute;
    width: 100%;
}

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

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

Issue with displaying personalized radio buttons

I added a custom radio button, but it's not showing up. It seems to work when arranged like this: <label> <input type="radio" name="gender" /> <span>Female</span> </label> Why isn't it working? Is there somethin ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Within an ng-repeat loop, I'm evaluating whether comparing numbers would be quicker than comparing strings

Utilizing this logic for basic template operations in Angular 1.5: <p ng-if="myData.type !== 'customer'"></p> Considering performance, would it be more efficient to use numerical comparison instead of string comparison like: <p ...

Steps to extract a hash from a document's URL

The following code is used: jQuery(document).ready(function() { console.log($(this)); }); After running this code, the object displayed in the console is: [Document mypage.html#weather] How can I retrieve the last ID from this object? In this ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

The term "Ext" has not been recognized or defined

Currently, I am facing an issue while attempting to integrate a TinyMCE plugin with ExtJs. I found a helpful demo example at this link, which I followed closely. However, my implementation is failing as I am receiving an error message stating "Ext is not ...

The grid elements are not in perfect alignment

I'm having trouble aligning the <p> element to the left and the image to the right. The image is not aligning properly with the fourth column, so I need to figure out how to fix that. .content{ display: grid; grid-template-columns: 25% 25 ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

Align the label vertically with the corresponding input field

I am currently in the process of revamping an old HTML form to eliminate the use of tables. I found a solution on this site to give the label a fixed width, and here is how it looks in the current code: HTML <div id="form"> <label for="field ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

Difficulty in displaying Font Awesome Unicode on website

I am struggling to populate a list with Font Awesome icons 4.7.0 in my HTML code using Bootstrap. Strangely, only the first icon is displayed while the rest remain invisible. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font- ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

Enhance the interoperability of Babel with Express.js by steering clear of relative

My current approach to imports is as follows: import router from '../../app/routes' Is there a way to avoid using ../../, for example: import router from 'app/routes'? In typescript, I can achieve this with the following configuratio ...

Displaying a video in fullscreen on a webpage

Struggling to achieve the desired result, seeking advice from experts. Looking to create a classic example like this: http://codepen.io/anon/pen/rWwaRE But want it embedded within blocks of text and possibly triggered by scrolling over it similar to this ...

When activating SSR in the Urql client, I encountered the following unexpected error: Server HTML should not include an <a> within a <div>

Unexpected Error Encountered while Rendering HTML at div at Styled(div) (Emotion Element) at div at Styled(div) (Emotion Element) at Flex (Chakra UI) at NavBar (Navigation Bar) at Index (Homepage) at withUrqlClient(Index) (Urql Client) at ColorModeProvider ...

The form submission did not yield any results

function calculateCost() { var projectorCost=0,price=0,quantity=0,discountPrice=0,totalCost=0; var modelName=document.getElementById('projectormodel').value; var quantity=document.getElementById('q ...

What is the best way to introduce a delay in the JSZip API loading process?

Is there a way to introduce a delay in the JSZip API while zipping multiple files? I need to add a pause between transferring files from the webserver. How can I include a delay in the code below? This is specifically for the browser and deploying binarie ...

Universal PM2 Configuration Settings in JSON Format

My current process involves initiating numerous Node.js processes using pm2. These processes are configured in a JSON file and started by executing pm2 start pm2.json Upon examining the JSON file provided below, it's evident that there is significan ...