Shift the Kid Element to an Alternate Holder

Currently, I am working on a project in Angular version 10. Within this app, there is a component that can be shared and will utilize the provided content through ng-content. Typically, this content will consist of a list of items such as divs or buttons.

I am looking to implement logic that will relocate the last child of a container to another container based on specific conditions (specifically, if the width becomes too narrow, the items need to be moved elsewhere). I have already set up logic that saves the last item in an array and removes it from the original container. However, I am unsure of how to effectively add this element to the new container.
I attempted using 'innerHTML', but this displayed object text instead of an HTML element.
Similarly, trying to set the children of the new container to the moved items (either by pushing them or setting them to a new object) did not produce the desired outcome.
I am at a loss for what other options to explore.

If you would like to take a look, here is a quick StackBlitz demo I created: https://stackblitz.com/edit/angular-ivy-ioqhhx?file=src/app/app.component.html

Answer №1

If you're looking for a more traditional JavaScript solution rather than something specific to Angular, you can check out this code snippet: https://stackblitz.com/edit/angular-ivy-hi3cfd?file=src%2Fapp%2Fapp.component.ts. Any other suggestions using built-in Angular tools are welcome too.

moveLastItem() {
    const lastIndex = this.startHereDiv.nativeElement.children.length - 1;
    const child = this.startHereDiv.nativeElement.children[lastIndex];
    this.moveHereDiv.nativeElement.appendChild(child);
}

In case you're wondering why your original code doesn't work, it's because

this.startHereDiv.nativeElement.children[lastIndex]
returns the object representation of the element, while [innerHTML] expects a raw string representation. Check the console log for an example. If you still prefer the [innerHTML] solution, you'll need to bypass the Angular DOM sanitizer as demonstrated here: https://stackblitz.com/edit/angular-ivy-c7ylm1?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

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

In Angular 2, leverage a variable within the @Component styles

Here is a plunker link for you to check out: https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview This is a basic angular application. I am using @ViewChild and nativeElement.offsetHeight to capture the height of a div. Can this number be used in the st ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

In Angular 6, users need to click twice for anchor scrolling to function properly

I've set up a simple layout on a really long page: <a href="/technicalmanagerreport/4e8485d9-5751-4684-9d24-0af2934dd390#h2">test</a> <h2 id="h2">LOL</h2> The issue I'm facing is that the first time I click the link, it ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

Unable to break down the property 'desks' of '(0 , _react.useContext)(...)' due to its undefined nature

Trying to mock DeskContext to include desks and checkIfUserPresent when calling useContext is causing an error to occur: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined TypeError: Cannot destruct ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...

Tips for retrieving information from a service in Ionic without the need to refresh the current page

home.ts uses the code snippet below in its OnInit() function to retrieve data from a service: this._http.get(this._url+this.SNO+"&"+this.randomno,{headers:headers}) .subscribe(data => {this.list=data.json(); A new record can be added on this pa ...

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

When compiling TypeScript, the exported module cannot be located

I've encountered an issue while working on my TypeScript project. Upon compiling my code with the following configuration: { "compilerOptions": { "target": "ESNext", "module": "ESNext", & ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date? let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + currentSelection.startTimeAMPM; let endTime = currentSelection.stopTimeHr + ":" + currentSele ...

Encountering the identical error message while attempting to execute my application: "Uncaught TypeError: this.microservicesModule.register is not a function."

Despite my repeated attempts to run the application, I am consistently encountering the following error message: "UnhandledPromiseRejectionWarning: TypeError: this.microservicesModule.register is not a function at NestApplication.registerModules ...

Create a dynamic Prisma data call by using the syntax: this.prisma['dataType'].count()

I'm currently working on implementing a counting function that can be utilized in all of my objects. In my 'core' file, Prisma is involved in this process. This allows me to execute commands like this.user.count() or this.company.count() I ...

Dealing with missing image sources in Angular 6 by catching errors and attempting to reset the source

When a user adds a blob to my list, sometimes the newly added image is still uploading when the list is refreshed. In this case, I catch the error and see the function starting at the right time: <img src="https://MyUrl/thumbnails/{{ blob.name }}" widt ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

Setting up Angular 2 for ASP.NET MVC: A Step-by-Step Guide

angular.io provides a setup guide for asp.net core at: https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html. However, I am trying to configure it for an asp.net mvc application. The Quick Start files are already present in the asp.net mvc te ...