Uncovering the perfect body proportions using Webpack and SystemJS

In the process of developing an Angular2 library that needs to work with both SystemJS and Webpack, I encountered a situation where I had to detect the height and width in pixels of the body tag to set dimensions for child tags. However, the behavior of Angular LifeCycle differed between SystemJS and Webpack, leading to different results. To illustrate this issue, I implemented the following code:

foo.component.ts

ngOnChanges() {
    console.log("ngOnChanges : " + document.body.clientHeight);
}

ngOnInit(){
    this.elHTML.setAttribute("direction", this.direction.toString());
    console.log("ngOnInit : " + document.body.clientHeight);
}

ngDoCheck() {
    console.log("ngDoCheck : " + document.body.clientHeight);
}

ngAfterContentInit() {
    console.log("ngAfterContentInit : " + document.body.clientHeight);
}

ngAfterContentChecked() {
    console.log("ngAfterContentChecked : " + document.body.clientHeight);
}

ngAfterViewInit() {
    console.log("ngAfterViewInit : " + document.body.clientHeight);
}

ngAfterViewChecked() {
    console.log("ngAfterViewChecked : " + document.body.clientHeight);
    this.widthHeightApply();
}

widthHeightApply(){
    var offsetWidth : number = document.body.clientWidth;
    var offsetHeight : number = document.body.clientHeight;
    ...
}

SystemJS result

ngOnChanges : 767
ngOnInit : 767
ngDoCheck : 767
ngAfterContentInit : 767
ngAfterContentChecked : 767

Webpack result

ngOnChanges : 40
ngOnInit : 40
ngDoCheck : 40
ngAfterContentInit : 206
ngAfterContentChecked : 206

Why do these different results occur? And how can we achieve consistency across SystemJS and Webpack?

Answer №1

I managed to solve the issue regarding the body width discrepancy between the actual value (1600px) and the displayed value ("1583px") in the console. This inconsistency is caused by the loading process of the Angular page. Prior to loading the Angular project, the index.html file lacks CSS styling, resulting in a margin for the body and a scrollbar being present. This leads to the shaking of the page during loading. The solution I found was to directly insert normalize.css in the head section of the index.html as shown below:

Manually Adding

index.html

<head>
 <meta charset="utf-8">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <title><%= htmlWebpackPlugin.options.title %></title>

 <meta name="description" content="<%= htmlWebpackPlugin.options.title %>">

 <% if (webpackConfig.htmlElements.headTags) { %>
   <!-- Configured Head Tags -->
   <%= webpackConfig.htmlElements.headTags %>
 <% } %>

 <!-- base url -->
 <base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">

 <!-- Normalize.css (the solution) -->
 <link rel="stylesheet" type="text/css" href="./styles/normalize.css" />
</head>

Gulp Injection Using Library

In my scenario, I am creating an npm package. During installation, the gulpfile.js of my library injects this line of CSS code into the index.html file. I utilized gulp-insert-lines to achieve this like so:

package.json

{
 ...
 "scripts": {
   "postinstall": "gulp install --gulpfile gulpfile.js",
 ...

}

gulpfile.js

var insertLines = require('gulp-insert-lines');
... 
gulp.task('install', function() { 
     return gulp.src(indexPath + 'index.html', {base: './'})
                  .pipe(insertLines({
                  'before': /<\/head>$/,
                  'lineBefore': '<link rel="stylesheet" type="text/css" href="./styles/normalize.css" />'
            }))
            .pipe(gulp.dest('./'));
 });

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

Error encountered in Vue code, lacks default export on Editor Terminal

I'm not experiencing any issues in the browser, I am getting the desired output. However, why does this keep showing up in the editor terminal? Any assistance would be greatly appreciated. Error - No Default Export: The module "/vue3/src/components/ ...

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 ...

Is using global variables as a namespace a good practice? Creating ambient TypeScript definitions in StarUML

I'm currently working on creating TypeScript type definitions for the StarUML tool. While I've been successful in defining most of the API, I've hit a roadblock when it comes to linking a JavaScript global variable ("type" in this case) with ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

The use of data binding can lead to the error known as ExpressionChangedAfterItHasBeen

Just getting started with Angular 4 and encountering an ExpressionChangedAfterItHasBeenCheckedError in my data binding field. Here's the code snippet: <form> <div> <h2>Hello {{input.value}}</h2> <input type="text" [valu ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Can an Angular 6 application be integrated into a Umbraco project?

I am currently working on an Umbraco Project that serves as an informative website. Recently, there has been a request to incorporate e-services (interactive HTML forms) into the site, which require either Angular 6 or Ajax. In a previous project, I utili ...

The element type 'ReactElement<any>' does not match a JSX element constructor function. 'undefined' cannot be assigned to type 'Element | null'

After attempting the suggested fix of deleting node_modules/ and yarn.lock, then reinstalling everything, I still cannot resolve the issue. I am currently developing a basic router that renders children based on a certain prop: import React, { Fragment } ...

Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png Within the collection, I wished to include an additional property to the objects. To achieve this, I utilized the map function: returnArray = returnArray.map((obj) => { obj.active = "fal ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

What is causing the dysfunction of angular2 form when used with the HTML <form> tag?

Can someone explain the strange behavior of the <form> element in ng2 to me? I have noticed something odd and need some clarification :) To demonstrate, I have created a simple Plunker example at this link: https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD ...

Possible revision: "Dynamic property naming in TypeScript interface based on specified type"

The concept might seem complex, but here's the gist of it. I have a User interface that may or may not contain certain properties depending on where it is fetched from. For example, there are optional properties like role and client_details. export i ...

Having Trouble Displaying Material UI Icons in Your React App? Here's Why: "Invalid Objects as React Children"

I have been working on a basic app that showcases information about a patient. In this specific component, I am only displaying the name, occupation, and a symbol from Material UI to indicate whether the patient is male or female. However, when I attempt ...

When deploying my Angular project, I am unable to access my files

I have been facing challenges while trying to deploy my web application with the frontend being Angular. The issue I am encountering is that I cannot access my JSON file located in the assets folder. Below is the function I am using to retrieve data from ...

How can I adjust the font size property for Material UI Icons through typing?

I put together the code snippet below, and I'm trying to define a specific type for the custom iconFontSize prop. Can someone guide me on how to achieve this? import { SvgIconComponent } from '@mui/icons-material' import { Typography, Typogr ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

Leveraging the power of mat-option and mat-radio-button within a mat-select or mat-selection-list

I'm currently working on a unique form element that combines checkboxes and radio buttons to create a multi-level selection feature. For instance, you can use it to configure properties for a car where a radio option (Digital or FM) is dependent on t ...

Angular CLI integrated with Isotope version 2

I am facing difficulties when using the isotope-layout module with Angular CLI. To install the module, I used the command: npm install isotope-layout --save After installation, I added the script in my .angular-cli.json file: "scripts": [ ... " ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...