Array modification update

Struggling with adding an object to the objectListDrawArea array outside of the original class. The object is added successfully, but my *ngFor loop cannot find it. I'm stumped on how to resolve this issue - should I use Observable? If so, can you provide an example in the comments? Thank you!

ao-bar.component.ts

import { AoBarService } from './ao-bar.service';
import { DrawAreaComponent } from '../../../draw-area/draw-area/draw-area.component';

@Component({
  selector: 'app-ao-bar',
  templateUrl: './ao-bar.component.html',
  styleUrls: ['./ao-bar.component.sass']
})
export class AoBarComponent implements OnInit {

  objectsList: object[] = new Array();

  showObjectsList: boolean;

  drawAreaComponent: DrawAreaComponent = new DrawAreaComponent();

  constructor(private service: AoBarService) { 
    this.service.getObject(this.objectsList);
  }

  ngOnInit() {
    console.log(this.objectsList, ' AoBarComponent');
  }

  private onShowObjectsList() {
    this.showObjectsList = !this.showObjectsList;
  }

  public onDragEnd(event: DragEvent): void {
    console.log('drag end', event);   

    if (this.drawAreaComponent.onDragEnter) {

      for (let object of this.objectsList) {

        if (object.name == event.path[0].nextElementSibling.innerText) {

          object.settings.x = event.x;
          object.settings.y = event.y;

          this.drawAreaComponent.createObject(object);
        }
      }  
    }
  }


}

draw-area.component.ts:

import { Component, OnInit } from '@angular/core';
import { CdkDragEnd } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-draw-area',
  templateUrl: './draw-area.component.html',
  styleUrls: ['./draw-area.component.sass']
})
export class DrawAreaComponent implements OnInit {

  objectsList: object[] = new Array();

  constructor() {

  }

  ngOnInit() {

  }

  public onDragEnter(event: DragEvent): boolean {
    console.log('drag enter', event);

    return true;
  }

  public onDragEnd(event: CdkDragEnd): void {
    console.log(event);
  }

  public createObject(objectToCreate: object): void {
    this.objectsList.push(objectToCreate);

    console.log(`Current List: ${this.objectsList}`);
  }
}

draw-area.component.html :

<div id="DrawAreaComponent">
  <div 
    class="example-boundary"
    (dragenter)="onDragEnter($event)"  
  >

    <div 
      id="ContainerObject" 
      *ngFor="let object of objectsList | async"
      cdkDragBoundary=".example-boundary"
      cdkDrag
      (cdkDragEnded)="onDragEnd($event)"
    >
      <img id="ImgObject" [src]="object.imgUrl">
    </div> 
  </div>
</div>

Answer №1

There seems to be an issue with change detection.

Instead of using

this.objectsList.push(objectToCreate);

Try

this.objectsList = [...this.objectsList, objectToCreate];
and see if it resolves the problem.

Make sure to educate yourself more on change detection for better understanding.

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

Tips for patiently waiting for a method to be executed

I have encountered a situation where I need to ensure that the result of two methods is awaited before proceeding with the rest of the code execution. I attempted to use the async keyword before the function name and await before the GetNavigationData() me ...

Having trouble retrieving files from an Angular2 service

I am facing an issue in creating an Angular2 service for downloading files from the server. I have a table where each record represents a single file. When clicking on a specific record, the download method is called: download(r: FileObject) { this.re ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

Angular - utilizing subscription within a for-loop to determine completion

Below is the code I am using to generate sticky notes: update() { this.tab3Service.updateStickyNote(this.stickyNoteUserConnection.stickyNote).subscribe(response => { const updatedStickyNote: StickyNote = response; for(let i = 0; i < this.stickyNo ...

Is there a way to convert a 2D array into a 3D array using Python?

I am attempting to visualize a two-dimensional array representing a pyramid in three-dimensional space. I could easily achieve this using the mesh() function in Matlab, but I am struggling to do it in Python. import numpy as np import matplotlib.pyplot a ...

Customize the datepicker locale in Valor

Currently, I am working with Angular2 and typescript alongside the Valor datepicker. Unfortunately, the datepicker does not have the necessary locale built-in. After some research, I discovered that the essential JavaScript file containing the locale infor ...

Tips for passing data between two components in React Router and outlet without the need for higher order functions

In my project, I have developed two components: one is named <Flights/> and the other is called <FlightResults/>. The Flights component serves as a context provider for the entire application. const Flights = () => { return ( <Flig ...

Arranging strings in descending order using Typescript

I was attempting to arrange a string[] in a descending order. This is what I have come up with so far: let values = ["Saab", "Volvo", "BMW"]; // example values.sort(); values.reverse(); Although this method is effective, I am wondering if there is a mo ...

How to bypass or exclude a value in a numpy array?

I am working with pixel values stored in a h5 file, extracting the data and creating a histogram using numpy. The array contains a specific no-data value of 99999, whereas the rest of the data ranges from -40 to 20. To ensure the no-data value does not aff ...

Disappearing act: Ionic tabs mysteriously disappear when the back button

Whenever I navigate in my ionic app, I notice that the tabs-bar disappears when I go to different pages and then return to the tabs. See Demo Code tab1 Here is a sample link to navigate to other pages: <ion-label routerDirection="forward" [routerLi ...

Merge attributes from objects within an array

I am seeking assistance with a basic task in TypeScript as a newcomer to the language. My challenge involves manipulating an array of objects like this: // Sample data let boop = [ {a: 5, b: 10}, {a: 7, c: 8}, {a: 6, b: 7, c: 9} ]; My objectiv ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...

What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opene ...

What is the method for assigning a value to a reactive form in Angular?

I need assistance with updating a user profile page by using patchValue to display data in the onInit function when the component is initialized. Here's the code snippet I have: I chose to use patchValue because the response data includes other inform ...

Leverage the power of gRPC with Node.js and TypeScript for seamless

I'm trying to implement GRPC in a Node.js and Typescript project, but I'm facing an issue with generating proto files on Windows 10 using npm. I need to run the file transpile-proto-ts.sh: #!/usr/bin/env bash OUT_DIR="./src" TS_OUT_DIR="./src" ...

Ways to retrieve JSON data in a flutter app

I have received JSON data from a server that I need to fetch and configure in both a Pageview Builder (horizontal scroll) and a Listview Builder (vertical scroll) for a Flutter application. The Listview Builder is nested within the Pageview Builder, which ...

Combining multiple arrays of objects using multiple keys with Angular 9 and Typescript

I have two JSON objects (displayed here with JSON.stringify(array of objects)) GPRows data is [ { "shopName":"Testing One", "state":"NSW", "yearMonth":"20203", "id& ...

Sharing code between a node.js server and browser with Typescript: A step-by-step guide

I have an exciting project in mind to develop a multiplayer javascript game using a node.js server (with socket.io) and I am looking for a way to share code, specifically classes, between the web client and the server. Luckily, I came across this resource: ...

The ko.mapping function is throwing an error because it cannot access the property 'fromJS' which is undefined

I am currently exploring typescript and attempting to integrate knockout.mapping into my project, but I'm facing some challenges. Despite installing the necessary libraries for knockout and knockout.mapping, along with their respective "@types" decla ...

gdb: encountered an issue reading a variable within an array during debugging in VS Code

I'm struggling with a technical issue when trying to inspect the contents of an array during debugging. Instead of displaying characters, I am only seeing dots. Below is my code snippet: #include <stdio.h> int main() { char str[100] = {0}; ...