Angular Universal causing issues with updating the DOM component

@Component({
  selector: 'mh-feature-popup',
  template: `
  <div class="full">
  <div>
    <div class="container-fluid" [@featurepop]="state">
      <div class="row">
        <div class="col-xs-12 col-md-4 col-md-offset-4 popup">
          <div class="row">
            <div id="shadow-card">
                <div class="col-xs-12 dialog-header hidden-md hidden-lg">
                    <div class="col-xs-1 skeleton hidden-md hidden-lg clickCursor" (click)="toggleState()">
                        <div class="close"></div>
                    </div>
                    <div class="text_heading col-xs-10">
                        <span *ngIf="name">{{name}}</span>
                    </div>
                </div>
                <div class="row dialog-content">
                    <div class="dialog-title skeleton col-md-10 col-md-push-1 hidden-xs hidden-sm">
                        <span *ngIf="name">{{name}}</span>
                    </div>
                    <div class="col-md-2 skeleton hidden-xs hidden-sm clickCursor" (click)="toggleState()">
                        <div class="close"></div>
                    </div>
                </div>
                <div *ngIf="data" #data_value>{{data}}
                </div>
            </div>
          </div>
        </div> 
      </div>
    </div>
  </div>
</div>
        `,
styles:[`
.full{
    background-color: rgba(0,0,0,0.2);
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
}
`],
providers:[ ApiService ],
animations: [
  trigger('featurepop', [
    state('inactive', style({
      transform: 'scale(0)'
    })),
    state('active', style({
      transform: 'scale(1)'
    })),
    transition('inactive => active', [
      animate(250)
    ]),
    transition('active => inactive', [
      animate(250)
    ])
  ])
]
})
 export class FeaturePopUpComponent {
  state = 'inactive';
  @Input()
      data;

  @Input()
      name;

  show(a,b,c){
      this._api.get(a,b,c).subscribe(
          data => {
              this.data = {'data': a};
              this.name = {'name': b};
              console.log(this.data);
          },
          err => console.log(err),
          () => {
              this._zone.run(() => {
                  this.rend.setElementStyle(this.element.nativeElement,"display","block");
                  this.toggle();
                  console.log(this.state);
              });

          }
      );

  }

 }

The feature of this component is to display a pop-up when the show() function is invoked with content obtained from an API call.

Although the show() function is functional, there seems to be an issue as the received data doesn't populate in the component's empty pop-up https://i.stack.imgur.com/Cuwtk.jpg.

Interestingly, changing the browser screen size causes the data to appear on the pop-up https://i.stack.imgur.com/aztYP.jpg.

However, the onChange() method triggers only when altering the screen size, not upon data changes. Various attempts including using JSON objects for data, employing changeDetection.Ref and NgZone, as well as implementing ngDoCheck() have been unsuccessful in resolving this issue.

This implementation utilizes the angular-universal starter kit. Assistance in addressing this issue via a jsfiddle or similar approach would be greatly appreciated.

Answer №1

This approach should be effective. I recommend familiarizing yourself with @Inputs.

If you simply want to display {{name}} in the HTML, all you need to do is define the name variable in the TypeScript file, rather than within data:{name:'aaa'}.

Link to the updated Plunker: https://plnkr.co/edit/owx397i2mLGBZ46oioQ1?p=preview

//our root app component
import {
  Component,
  NgModule,
  VERSION,
  ViewChild,
  forwardRef,
  Input,
  trigger,
  state,
  style,
  animate,
  transition,
  Inject,
  Renderer,
  ElementRef
} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';


@Component({
  selector: 'feature-popup',
  template: `
    <div class="full">
      <div>
        <div class="container-fluid" [@featurepop]="state">
          <div class="row">
            <div class="col-xs-12 col-md-4 col-md-offset-4 popup">
              <div class="row">
                <div id="shadow-card">
                  <div class="col-xs-12 dialog-header hidden-md hidden-lg">
                    <div class="col-xs-1 skeleton hidden-md hidden-lg clickCursor" (click)="toggle()">
                      <div class="close"></div>
                    </div>
                    <div class="text_heading col-xs-10">
                      <span *ngIf="name">{{name}}</span>
                    </div>
                  </div>
                  <div class="row dialog-content">
                    <div class="dialog-title skeleton col-md-10 col-md-push-1 hidden-xs hidden-sm">
                      <span *ngIf="name">{{name}}</span>
                    </div>
                    <div class="col-md-2 skeleton hidden-xs hidden-sm clickCursor" (click)="toggle()">
                      <div class="close"></div>
                    </div>
                  </div>
                  <div *ngIf="data" #data_value>{{data}}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .full {
      background-color: rgba(0, 0, 0, 0.2);
      width: 100vw;
      height: 100vh;
      position: fixed;
      top: 0;
      left: 0;
      z-index: 999;
    }

    #shadow-card {
      background-color: white;
      height: 350px;
      box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
      position: absolute;
      top: 50%;
      left: 50%;
      display: inline-block;
      margin-top: 100px;
      margin-left: -200px;
    }
  `],
  providers: [],
  animations: [
    trigger('featurepop', [
      state('inactive', style({
        transform: 'scale(0)'
      })),
      state('active', style({
        transform: 'scale(1)'
      })),
      transition('inactive => active', [
        animate(250)
      ]),
      transition('active => inactive', [
        animate(250)
      ])
    ])
  ]
})
export class FeaturePopUpComponent {
  state = 'inactive';
  data;
  name;

  constructor(private element: ElementRef,
              private rend: Renderer) {
    this.rend.setElementStyle(element.nativeElement, "display", "none");
  }

  show(a, b) {
    this.data = a;
    this.name = b;
    this.rend.setElementStyle(this.element.nativeElement, "display", "block");
    this.toggle();
    console.log(this.state);

  }

  toggle() {
    this.state = (this.state === 'active' ? 'inactive' : 'active');
  }

}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="show()">Open me</h2>
      <feature-popup></feature-popup>
    </div>
  `,
})
export class App {
  @ViewChild(FeaturePopUpComponent) popup: FeaturePopUpComponent;
  a;
  b;

  constructor() {
  }

  show() {
    this.a = 'hi';
    this.b = 'hello';
    this.popup.show(this.a, this.b);
  }
}

@NgModule({
  imports: [BrowserModule, BrowserAnimationsModule],
  declarations: [App, FeaturePopUpComponent],
  bootstrap: [App]
})
export class AppModule {
}

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

Looking to set up an event handler for the browser's back button in next.js?

When my modal opens, it adds a hash to the URL like example.com/#modal. I want to be able to recognize when the back button is clicked in the browser so I can toggle the state of the modal. The challenge is that since I am using next.js (server-side rend ...

I am experiencing an issue where the result is not appearing on the input tag within my

<script> <form action="do-add-cek.php" id="myForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label> ...

Is there a way to utilize the reset() function within an input form?

Is there a way to automatically reset the textbox when submitting a value? Below is my code: <!DOCTYPE html> <html> <body> <ul id="myList"> </ul> <input type="text" id="myText" value="&q ...

Retrieving data through an Angular Material Table by employing an HTTP GET request

I am working with an Angular Material table and need to retrieve data from a service. Below is the code for the service. import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Message } from '../messag ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...

The subscribe method in Angular TS may be marked as deprecated, but worry not as it is still

I have developed a function that retrieves new data from a service file each time it is called. Here is how the function looks: onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) => { if (response?.d ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Challenges arise when integrating ng-model with Angular Chosen

I'm working with a table that lists users, each row ending with a button that triggers a popup form. Inside the popup, I'm using a multiple select feature with Angular Chosen to display each user's 'interests'. However, despite fet ...

Dynamic value in Angular select using ng-initExperience the power of Angular select

When working with Angular, I encountered an issue trying to set a default value for a select box using ng-init from an object that is generated during runtime. Here's the code snippet that's causing me trouble: <select ng-model= ...

Identify unique MongoDb instances within an array of data

My list contains various unique items - search = alluk.distinct('Object of search') I am interested in counting each item individually. Presently, I am counting them manually in the following way - alluk.find({'Object of search':&ap ...

After clicking on the About page in Vue, my data seems to vanish into thin air

The Vue router is up and running with two pages: Home and About. Everything seems to be functioning properly, however, when I navigate to the About page and then return to the Home page, the data is lost. The page isn't refreshing, I'm simply swi ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Sending arrays in JSON format using Node.js Express (res.json)

I have a code snippet like this: app.get('/orders/:pizzeriaID/:status', async (req, res) => { try { const requestedOrderByPizzeriaID = req.params['pizzeriaID']; const requestedOrderByStatus = req.params['status']; ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

The (ReactJS + Redux) form fails to load when the /new segment is appended to the URL

I'm currently working on a project using React, Redux, and Rails. I've encountered an issue with loading the form. In my App.js file, I have set up a Router that defines the routes. import React, { Component } from 'react'; import { Br ...

I'm in the process of developing a React application that will display live sensor data in graph form

My current project involves building a react app that visualizes real-time data from IoT sensors, including temperature, humidity, and pressure. I want the app to store this data so users can log in at any time to view specific information based on time, d ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

Appear and disappear div

I am seeking to achieve a specific goal: I want to fade in a div with text after a certain number of seconds, then fade it out. I also want to repeat this process for 4 other divs, ensuring that they do not interfere with each other by appearing while the ...

What is preventing me from sending back an array of objects with an async function?

Working with node.js, my goal is to retrieve a list of bid and ask prices from a trading exchange website within an async function. While I can successfully log the object data using console.info() within the foreach statement on each iteration, when attem ...

Issue with the DocPad plugin for Gulp

I'm encountering an issue while trying to utilize the gulp docpad plugin. When I run docpad run, the following error message is displayed: Error: spawn UNKNOWN at exports._errnoException (util.js:837:11) at ChildProcess.spawn (internal/child_process. ...