#StackBounty: #javascript #angular #angular-material #virtualscroll #angular-cdk-virtual-scroll Scroll to bottom with cdk-virtual-scrol…

Bounty: 100


Display a list of messages and scroll to bottom when a new message is received.


With virtual scroll I have to set the [itemSize] property, but for me it is not a static value:

  • When a message is too long for one line it breaks in multiple, so its height changes.
  • I have different types of messages with different heights (system messages for example).

Also, I am using ng-content to insert a button from the parent to load previous messages. What I see is that, when _scrollToBottom is invoked, instead of taking me to the bottom, it takes me to a bit higher. I suspect this is because of the button height.

I have read this autosize scroll strategy issue from Angular: https://github.com/angular/components/issues/10113; but I am not sure this will solve my problem.

Any idea of what I could do will be welcome.


Codesandbox: https://codesandbox.io/s/angular-virtual-scroll-biwn6

  • While messages are being received, scroll up.
  • When the next message is loaded, instead of scrolling to bottom, the virtual-scroll stops a little higher.

Here is my code:


<cdk-virtual-scroll-viewport class="w-100 h-100" [itemSize]="65" #virtualScroll>
    <!-- HERE will go the load previous messages button -->

  <ul class="h-100 w-100">
        let message of displayMessages$ | async;
        trackBy: messagesTrackByFn
        'is-agent': isAgentMessage(message),
        'is-client': isCustomerMessage(message),
        'is-system': isSystemMessage(message),
      <ng-container *ngIf="isSystemMessage(message)">
          <mat-icon [inline]="true">error_outline</mat-icon>
          <span [innerHTML]="message.body"></span>
      <!-- ... more types of messages in ng-container elements -->


export class MessageListComponent implements OnDestroy {
  @ViewChild("virtualScroll", { static: true })
  public virtualScrollViewport: CdkVirtualScrollViewport;
  private _lastMessageId = null;
  @Input() set messages$(value: Observable<Message[]>) {
    if (!!value) {
      this.displayMessages$ = value.pipe(
        shareReplay({ refCount: true, bufferSize: 1 }),
        tap((messages) => {
          if (!messages || !messages.length) {
          const lastMessage = messages[messages.length - 1];
          // Because of virtual-scroll, the number of items displayed is always the same
          // so to check if new elements have been added I compare the last message id
          if (!lastMessage.id || lastMessage.id !== this._lastMessageId) {
            this._lastMessageId = lastMessage.id;

  //   ...

  private _scrollToBottom() {
    // I use setTimeout because this has to be executed after the view has rendered the elements
      () =>
          bottom: 0,
          behavior: "auto",


package.json dependencies:

"dependencies": {
    "@angular/animations": "~8.2.14",
    "@angular/cdk": "^8.2.3",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^8.2.3",
    "@angular/material-moment-adapter": "^8.2.3",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "matchmedia-polyfill": "^0.3.2",
    "rxjs": "~6.4.0",
    "zone.js": "~0.9.1"
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.25",
    "@angular/cli": "~8.3.26",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@morphe/build-angular": "^3.1.0",
    "@morphe/schematic-angular": "^3.0.0-rc.2",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.9.5",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "tslint-sonarts": "^1.9.0",
    "typescript": "~3.5.3"

Get this bounty!!!

#StackBounty: #angular #algolia #instantsearch.js How to get specific data from algolia in angular

Bounty: 50

I’m using algolia in angular.
I’m trying to get only a specific record from algolia.
I have a product_id and want record of that product_id
Here is what I have done so far –
.html file

    <ais-instantsearch [conproducts]>
        <ais-configure [searchParameters]="{ hitsPerPage: 1 }"></ais-configure>
           <ng-template let-hits="hits">
           <div class="row">
                <div class="col-lg-2 col-md-3 col-sm-4 col-6"*ngFor="let hit of hits">

.ts file

    const searchClient = algoliasearch(
    export class ProductsComponent implements OnInit {
      productsConfig = {
          indexName: 'products',

How to get specific data by id in the algolia?
Any help would be appreciated,

Get this bounty!!!

#StackBounty: #angular #iis #url-rewriting #web-hosting #angular-components Site can't be reached error-After hosting Angular app o…

Bounty: 50

Recently I have hosted an angular(version 10) web app on our testing server (IIS 8.0). And also installed URL Rewrite Module in IIS also.

And following is my web.config which was added for rules.

      <rule name="Redirect all requests" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <action type="Rewrite" url="./index.html" />
  <directoryBrowse enabled="true" />
  <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
    <customErrors mode="On" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="/index.html" />

But after hosting the application the site is running but continuously getting following error site can’t be reached as shown in below screen shot. After getting error the URL is automatically reloading within seconds and then site is working as expected.

site can't be reached error

Following is my app pool setting.

App pool config

What is the reason for this error ? It is happening without idle time also. Am I missing any IIS setting (other apps which are published via visual studio are running fine only problem with this application) ? or need to add any other URL writing rule? or any settings need to included on my angular app? Please help me.

Get this bounty!!!

#StackBounty: #angular #asp.net-core How can update a model with images attach?

Bounty: 50

i create a component edit a model has upload imgages.

this is edit.component.html

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  <div class="form-group">
    <table *ngIf="movie">
          <input type="text" class="form-control" ngModel="{{movie.id}}" name="id" />
          <input type="text" class="form-control ng-untouched ng-pristine ng-valid"
                 [(ngModel)]="movie.title" name="title" #title="ngModel" />
          <div [hidden]="title.valid || title.pristine"
               class="alert alert-danger">
            Name is required
        <td><input type="number" class="form-control" [(ngModel)]="movie.price" name="price" /></td>
        <td><input type="text" class="form-control" [(ngModel)]="movie.rating" name="rating" /></td>
        <td><input type="text" class="form-control" [(ngModel)]="movie.genre" name="genre"/></td>
          <img [src]="imgURL" height="100" *ngIf="imgURL">
          <input type="file" id="file" (change)="handleFileInput($event.target.files)" >
        <td><input type="submit" [disabled]="!heroForm.form.valid" (click)="Update()" value="Update" /></td>

this is edit.component.ts

export class EditMovieComponent {    

  constructor(private MoviesService: MoviesService, private route: ActivatedRoute) { }
  movie: any; 

  fileToUpload: File = null;
  imgURL: any;

  ngOnInit(): void {
    var id = this.route.snapshot.paramMap.get('id');
    this.imgURL ="assets/images/" + id + ".png";    

  getdata(id) {
    this.MoviesService.getDataItem(id).subscribe((data: any) => {
      this.movie = data;
  Update() {        

    this.MoviesService.putData(this.movie.id, this.movie).subscribe((data: any[]) => {
      //this.data = data;
      if (data == null)
  handleFileInput(files: FileList) {
    //this.fileToUpload = files.item(0);
    var reader = new FileReader();   
    reader.onload = (_event) => {
      this.imgURL = reader.result;

This is MovieService:

export class MoviesService {

  constructor(private http: HttpClient) { }
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
  getData() {
    return this.http.get('/api/Movies');  //https://localhost:44352/ webapi host url  
  getDataItem(id) {
    return this.http.get('/api/Movies/'+id); 
  putData(id, formData) {
    return this.http.put('/api/Movies/' + id, formData);

This is controller:

        public async Task<IActionResult> PutMovie(int id, Movie movie)
            if (id != movie.Id)
                return BadRequest();

            _context.Entry(movie).State = EntityState.Modified;

                await _context.SaveChangesAsync();
            catch (DbUpdateConcurrencyException)
                if (!MovieExists(id))
                    return NotFound();

            return NoContent();

this is Model class:

 public class Movie
        public int? Id { get; set; }
        public string Title { get; set; }     
        public string Genre { get; set; }      
        public decimal Price { get; set; }       
        public string Rating { get; set; }       

i want upload images when put model data.

How can put model with images attach?

Get this bounty!!!

#StackBounty: #php #node.js #angular #typescript Not able to pass JWT authorization using Angular8

Bounty: 250

Below php api script given by client when I run into local then Static data storing in api server successfully.

    //creating payload parameters:
    $classTitle = 'Demo Class on 3rd April, 2020';
    $classInfo = 'This is a demo class scheduled to understand API';
    $classDateTime = '2020-11-12 11:30 AM';
    $timezone = 'Asia/Kolkata';
    $classDuration = 15;
    $classRecording = 'yes';
    $classAutoStart = false;
    $recordingAutoStart = false;
    $classVideoRes = 720;

    $apiKey = '12345';
    $secretKey = '12345';

    // Create token header as a JSON string
    $header = json_encode(['alg' => 'HS256','typ' => 'JWT']); // ensure to place first alg part and next typ part

    // Create token payload as a JSON string
    $payload = json_encode(['classTitle' => $classTitle ,'classInfo' => $classInfo ,'classDateTime' => $classDateTime ,'timezone' => $timezone ,'classDuration' => $classDuration ,'classRecording' => $classRecording ,'classAutoStart' => $classAutoStart ,'recordingAutoStart' => $recordingAutoStart ,'classVideoRes' => $classVideoRes ,'apiKey' => $apiKey]);

    // Encode Header to Base64Url String
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

    // Encode Payload to Base64Url String
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

    // Create Signature Hash
    $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secretKey , true);

    // Encode Signature to Base64Url String
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

    // creating JWT token variable
    $jwt_token = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

    // creating authorization varibale
    $authorization = 'Bearer '.$jwt_token;


    <script type="text/javascript">
        type: "POST",
         url: 'https://xyz/client/schedule',
        contentType: 'application/json',
        data: JSON.stringify({
            "apiKey": "12345"
        dataType : 'json',
        headers: {
        'authorization': '<?php echo $authorization; ?>'
        success: function(retval)
        // alert(retval);
        // var success = retval.success;

Directly i pass parameters to above php api then also its not working, my senior told me you have to call above code from angular I wrote code but i am not able to store successfully below is my angular code.

Below is my model class

export class Schedule1 {

classTitle: string;
classInfo: string;
classDateTime: string;
timezone: string;
classDuration: number;
classAutoStart: boolean;
recordingAutoStart: boolean;
classVideoRes: number;
   constructor() {


Below is component.ts on button click passing static values

import { Schedule1 } from '../Models/Schedule1.model'

   Schedule1: Schedule1 = new Schedule1();

    addSchedule(scheduleForm: NgForm): void {

    //static data parameter passing
    this.Schedule1.classTitle='hi Class on 3rd April, 2020';
    this.Schedule1.classInfo= 'This is a demo class scheduled to understand API';
    this.Schedule1.classDateTime= '2020-11-12 11:30 AM';
    this.Schedule1.timezone= 'Asia/Kolkata';
    this.Schedule1.classDuration= 15;
    this.Schedule1.classRecording= 'yes';
    this.Schedule1.classAutoStart= false;
    this.Schedule1.recordingAutoStart= false;
    this.Schedule1.classVideoRes= 720;

    //const data = JSON.stringify(this.Schedule1);
    const data = { 
    apiKey: "dcbf187d-bdfe-431b-8f60-fa19bf51cd85", 
    data:  JSON.stringify(this.Schedule1)

    this.subscription = this.userSvc
    .fetchData("https: //xyz.com/client/schedule", data)
    data => {
    // Data on Success
    console.log("data", data);
    error => {
    console.log("error", error);


Below is service.ts

  fetchData(url: string, data: any): Observable<any> {
    const headers = {
    Authorization: "Bearer "+"1234",
     "My-Custom-Header": "foobar",
    contentType: "application/json"

   return this.http.post(url, data, {

in console getting this error.

enter image description here

Get this bounty!!!

#StackBounty: #angular #ag-grid #ngoninit AG Grid : gridReady event not triggered when loading grid in a component via ComponentFactory…

Bounty: 100

On my Angular 10 app, I’m loading through the component factory resolver a component containing an AG Grid.

When I trigger the factory resolver through a button, everything works fine. The Grid is displayed and the gridReady event is fired correctly.

However if I trigger the component factory resolver through through ngOnInit() or ngAfterViewInit() etc., the gridReady event is not triggered and the grid is not displayed.

I tried to use the ChangeDetectorRef service to force a change detection, but that didn’t change anything.

This is the code for the component factory resolver:

export class PlannerComponent implements OnInit {
  @ViewChild('ordersContainer', {read: ViewContainerRef}) container: ViewContainerRef;
  public orders = [];

    private componentFactoryResolver: ComponentFactoryResolver,
    private httpClient: HttpClient
  ) { }

  ngOnInit(): void {

  loadOpenOrders() {
      .pipe(map((result: any) => {
        const orders = result._embedded.orders;
        orders.forEach((function (order) {

  onGridReady(params) {
    this.gridApi       = params.api;
    this.gridColumnApi = params.columnApi;

  addOrder() {
    // Create component dynamically inside the ng-template
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(OrderComponent);
    const newOrder         = this.container.createComponent(componentFactory);

    // Push the component so that we can keep track of which components are created

In the view, the component is loaded like this:

<div class="container">
  <div class="row">
    <div class="col-6">
      <div class="card card-custom gutter-b">
          style="width: 100%; height: 600px;"
          (gridReady)="onGridReady($event)"   <==== Only triggered through button click, but not on ngOnInit()
    <div class="col-6">
      <button class="btn btn-success mb-5" (click)="addOrder()">Add a new Order</button>
        <ng-template #ordersContainer>

Any help is appreciated 🙂

Get this bounty!!!

#StackBounty: #angular #typescript #visual-studio-code #tsconfig #tsconfig-paths VSCode / tslint does not resolve paths in tsconfig.json

Bounty: 100

vscode is somehow not honoring my tsconfig.json (for a couple of weeks now, it has been different. eiter my bad or vscode update…)

"compileOnSave": false,
"compilerOptions": {
    "baseUrl": "./",
    "paths": {
        "@foo-animation/*": [

enter image description here

Respectively in the Problems tab:

Cannot find module ‘@foo-animation/animation-micro’ or its corresponding type declarations. ts(2307)

Regular base paths (like @angular/core) are properly resolved, just my ‘custom’ ones are the problem…

Compiling, Building, Running… all works like a charm. So I believe from an angular/typescript-perspective everything is fine. (Also, my fellow developers using IntelliJ have no issues…) So it seems to boild down to „telling vscode (or tslint within) about it“…. :-/

My tsconfig.json sits in the root-folder of the project. the only thing is, that I use another tsconfig.app.json, which includes above tsconfig.json.

enter image description here

So is there a way to tell vscode (resp. tslint) where to look for it’s tsconfig.json (to encourage parsing those paths) ?

This SO question and this VSCode github issue might be related, but I still don’t know what to do.

Get this bounty!!!

#StackBounty: #node.js #angular #pagination #angular-module #angular-pagination JW Angular Pagination Doesn't Work if used in Featu…

Bounty: 50

I’m using Angular 10 and the JW Angular Pagination module works fine if I import it into app.module.ts and then use it in a view that uses the app.component.ts component. However, when I try to import it into a custom feature module and use a component that imports the feature module, the pagination element does not display in the view template. It seems that Angular cannot see the pagination module.


import { NgModule, Component, OnInit } from '@angular/core';
import { CoreModule } from "./core/core.module"
import { MessageModule } from "./messages/message.module";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import * as $ from 'jquery';
import { BrowserModule } from '@angular/platform-browser';
import { AuthService } from "./model/auth.service"
import { JwPaginationModule } from 'jw-angular-pagination';

  imports: [AppRoutingModule, MessageModule, CoreModule, BrowserModule, JwPaginationModule],
  declarations: [AppComponent,],  
  providers: [AuthService],
  bootstrap: [AppComponent]
export class AppModule {


import { NgModule } from "@angular/core";
import { ModelModule } from "../model/model.module";
import { FormsFeatureModule } from "../view/forms.module";
import { ViewFeatureModule } from "../view/view.module";
import { routing } from "../app.routing";
import { MessageModule } from "../messages/message.module";
import { MessageService } from "../messages/message.service";
import { Message } from "../messages/message.model";
import { AuthService } from "../model/auth.service";
import { EncrDecrService } from '../utils/EncrDecr.service';
import { CommonModule } from '@angular/common';

//import { NotFoundComponent } from "./notFound.component";
//import { UnsavedGuard } from './unsaved.guard';

  imports: [ModelModule, MessageModule, routing, FormsFeatureModule, ViewFeatureModule, CommonModule],
  declarations: [],
  exports: [ModelModule, FormsFeatureModule, ViewFeatureModule, MessageModule ],
  providers: [AuthService, EncrDecrService],

export class CoreModule {


import { NgModule } from "@angular/core";
import { FormsModule, Validators, FormGroup, FormBuilder, NgForm } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
//import { NotFoundComponent } from "./notFound.component";
//import { UnsavedGuard } from './unsaved.guard';
import { ActivatedRoute, Router } from "@angular/router";
import { AuthService } from "../model/auth.service";
import { JwPaginationModule } from 'jw-angular-pagination';

  imports: [FormsModule, ReactiveFormsModule, BrowserModule, RouterModule, JwPaginationModule],
  declarations: [],
  exports: [FormsModule, ReactiveFormsModule, RouterModule, JwPaginationModule],
  providers: [AuthService],

export class FormsFeatureModule {

  constructor(private router: Router) { }


import { RecipeViewComponent } from "../view/recipeView.component";
import { NgModule } from "@angular/core";
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HomePageComponent } from "./homePage.component";
import { AdminComponent } from "../admin/admin.component";
import { AuthService } from "../model/auth.service";
//import { NotFoundComponent } from "./notFound.component";
//import { UnsavedGuard } from './unsaved.guard';

  imports: [FormsModule, ReactiveFormsModule, BrowserModule, RouterModule],
  declarations: [RecipeViewComponent, HomePageComponent, AdminComponent],
  exports: [RecipeViewComponent, HomePageComponent,AdminComponent, RouterModule],
  providers: [AuthService],

export class ViewFeatureModule { }


import { Component, Inject, DoCheck, ChangeDetectorRef, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { ModelRepo } from "../model/repository.model";
import { Category } from "../model/category.model";
import { Ingredient } from "../model/ingredient.model";
import { RecipeBook } from "../model/recipeBook.model";
import { User } from "../model/user.model";
import { FormsFeatureModule } from "../view/forms.module"
import { ViewChild, ElementRef } from '@angular/core';
import { EncrDecrService } from '../utils/EncrDecr.service';
import { AppComponent } from '../app.component'
import { Observable, throwError } from "rxjs";

//import { MODES, SharedState, SHARED_STATE } from "./sharedState.model";
//import { Observer} from "rxjs"


    selector: "admin",
    templateUrl: "admin.component.html"


export class AdminComponent implements OnInit {
 ModNewCategory = new Category(0,"");
  ModNewIngredient = new Ingredient(0,"");
  ModNewRecipeBook = new RecipeBook();
  selectedConfig = "categories"; //initilze for first page load
  selectedCategoryOperation = "addCategory"; //initilze for first page load
  selectedIngredientOperation = "addIngredient"; //initilze for first page load
  selectedUserOperation = "addUser"; //initilze for first page load
  userRoles = new Array<string>("visitor", "member", "administrator");
  searchRole = "";
  defaultObject = new Object();
  public pageOfItems: Array<any>;
  public items = [];

  constructor(public dataRepo: ModelRepo, private EncrDecr: EncrDecrService, private appComponent:AppComponent, activeRoute: ActivatedRoute, public router: Router, public fieldValidator: FormsFeatureModule) {
    activeRoute.params.subscribe(params => {

      this.id = params["id"];
      this.mode = params["mode"];
      this.operation = params["operation"]
      if (this.operation != null && this.mode != null) {
        this.modifyItem(this.id, this.operation);
  ngOnInit() {
    // an example array of 150 items to be paged
  //  this.items = this.dataRepo.users;
    this.items = Array(150).fill(0).map((x, i) => ({ id: (i + 1), name: `Item ${i + 1}` }));

  onChangePage(pageOfItems: Array<any>) {
    // update current page of items
    alert('onChangePage got called');
    this.pageOfItems = pageOfItems;


   <div class="card text-center m-3">
      <h3 class="card-header">Angular  Pagination Example</h3>
      <div class="card-body">
        <div *ngFor="let item of pageOfItems">{{item.name}}</div>
      <div class="card-footer pb-0 pt-3">
        <jw-pagination [items]="items" (changePage)="onChangePage($event)"></jw-pagination>

enter image description here

Get this bounty!!!

#StackBounty: #angularjs #angular #angularjs-directive #angular-directive Convert angularjs directive to angular 10

Bounty: 50

I want to use this code in my angular project:

'use strict';

 * Floating text animation (random)
angular.module('g1b.text-animation', []).
directive('textAnimation', ['$document', '$interval', '$timeout', function ($document, $interval, $timeout) {
  return {
    restrict: 'A',
    compile: function () {
      return {
        pre: function () {},
        post: function (scope, element) {
          var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
          $interval(function () {
            for ( var i = 0; i < Math.floor(Math.random() * 5); i++ ) {
              var character = chars[Math.floor(Math.random() * chars.length)];
              var duration = Math.floor(Math.random() * 15);
              var offset = Math.floor(Math.random() * (45 - duration * 3)) + 3;
              var size = 12 + (15 - duration);
              var span = angular.element('<span class="animated-text" style="right:'+offset+'vw; font-size: '+size+'px; animation-duration:'+duration+'s">'+character+'</span>');
              $timeout(function (span) {
              }, duration * 1000, false, span);
          }, 250);

it also has a CSS file with it.
this code is basically a text animation.
my problem is I don’t know where to start.

this is what I’m trying to achieve:

this is the npm of it:


I’ve tried it on my own and this is what I have:

@ViewChildren('styleDiv', {read: ElementRef}) children: QueryList<ElementRef>;

  constructor(private renderer: Renderer2, private host: ElementRef) {

  ngOnInit(): void {

  ngAfterViewInit(): void {

  private animateBackground(): void {
    const renderer = this.renderer;
    const children = this.children;
    const host = this.host;
    const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
      'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    setInterval(() => {
      for (let i = 0; i < Math.floor(Math.random() * 5); i++) {
        const character = chars[Math.floor(Math.random() * chars.length)];
        const duration = Math.floor(Math.random() * 15);
        const offset = Math.floor(Math.random() * (45 - duration * 3)) + 3;
        const size = 12 + (15 - duration);
        const span = '<span class="animated-text" style="right:' + offset + 'vw; font-size: ' +
          +size + 'px; animation-duration:' + duration + 's">' + character + '</span>';
        this.children.first.nativeElement.insertAdjacentHTML('beforeend', span);
        setTimeout(() => {
          // renderer.removeChild(children.first.nativeElement.parentNode, children.first.nativeElement);
        }, duration * 1000, false, host, children, renderer);
    }, 250, host, children, renderer);

it works, but I do have a problem inside the set timeout function.
I’m able to add the span to the dom, but not able to remove it.

Get this bounty!!!

#StackBounty: #angular Angular budgets throw error but files do not reach size

Bounty: 50

In my Angular 8’s angular.json file I have set an initial budget for production:

"production": {
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": true,
    "buildOptimizer": true,
    "fileReplacements": [{
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
    "budgets": [{
        "type": "initial",
        "maximumWarning": "1.5mb",
        "maximumError": "1.6mb"
    "serviceWorker": true

When I run ng build --prod the output errors:

Console output

However, none of the files tagged as initial have reached mentioned file size, neither alone nor together:

enter image description here

What is happening? Why is this error being thrown?

Note 1: Files get generated after removing budgets and running exactly same command, otherwise they don’t get generated.

Note 2: Files generated seem to be duplicate, but that is Angular 8’s differential loading (es5/es2015).

Note 3: Files generated don’t even match in size with console output.

Get this bounty!!!