I'm struggling with deleting a row from a pushed Object in Angular 2 and could use some guidance

Let me start by explaining my current issue:

Initially, the problem was like this: , where it deleted the last created Object, Conditions in my case.

However, I need to be able to delete each condition separately. For example, as shown with the red box next to each row here:

import {Component, OnInit, DynamicComponentLoader, Input} from 'angular2/core';
import {Condition}    from './condition';

import {DateCondition}    from './datecondition.component';
import {StringCondition}    from './stringcondition.component';
import {SelectCondition}    from './selectcondition.component';
import {ConditionDetailComponent}    from './conditiondetail.component';

import {ConditionService} from './condition.service'

@Component({
    selector: 'condition-builder',
    templateUrl: 'app/conditionbuilder.component.html',
    directives: [ConditionDetailComponent],
})

export class ConditionBuilderComponent implements OnInit {
    conditions: Condition[] = [];
    catalog: Condition[] = [];

constructor(public _conditionService: ConditionService) { }

getConditions() {
    this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}

ngOnInit() {
    this.getConditions();
}

onChange(conditionsIndex, selectedCondition:string): void {
    this.conditions[conditionsIndex] = this.catalog.find(condition => condition.name == selectedCondition);
}

newCondition() {
    this.conditions.push(this.catalog[0]);
}

deleteCondition() {
    this.conditions.pop();
}
}

In the code above, I am importing getConditions with the object of conditions in my case. Can anyone advise on how best to handle this situation?

Now, I am looking to

import {Component, OnInit, Input, DynamicComponentLoader, ElementRef} from 'angular2/core';

import {Condition}    from './condition';

import {DateCondition}    from './datecondition.component';
import {StringCondition}    from './stringcondition.component';
import {SelectCondition}    from './selectcondition.component';
import {ConditionBuilderComponent} from "./conditionbuilder.component";

@Component({
    selector: 'condition-detail',
    template: '<div #child></div>'
    + '<a class="btn btn-danger" (click)="deleteCondition()"><i class="glyphicon glyphicon-minus"></i></a>'
})

export class ConditionDetailComponent implements OnInit  {
    @Input() condition: Condition;

    dcl:DynamicComponentLoader;
    elementRef:ElementRef;

    constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
        this.dcl = dcl;
        this.elementRef = elementRef;
    }

    ngOnInit() {
        this.dcl.loadIntoLocation(this.condition, this.elementRef, 'child');
    }

   deleteCondition() {
    HOW CAN I DELETE THE CONDITION ROW HERE?
}

Given the setup of the code, I hope it's clear for you to assist me. How does the deleteCondition method determine which row needs to be deleted and how can I remove it from the array shown in the code above?

I am hopeful that someone can provide guidance on this matter!

Answer №1

One way to handle this is by passing the list to the sub component and removing the current element from it. By doing this, the associated component in the loop will be eliminated.

  • Main Component:

    @Component({
      selector: 'my-app',
      template: `
        <div *ngFor="#elt of data">
          <my-component [elt]="elt" [data]="data"></my-component>
        </div>
      `,
      directives: [MyComponent]
    })
    export class AppComponent {
      constructor() {
        this.data = [
          {name: 'name1'},
          {name: 'name2'},
          {name: 'name3'},
          {name: 'name4'}
        ];
      }
    }
    
  • Child Component:

    @Component({
      selector: 'my-component',
      template: `
        <div>{{elt.name}} <span (click)="delete()">X</span></div>
      `
    })
    export class MyComponent {
      @Input()
      elt: any;
    
      @Input()
      data: any[];
    
      delete() {
        var index = this.data.indexOf(this.elt);
        this.data.splice(index, 1);
      }
    }
    

Check out this plunkr for a live example: https://plnkr.co/edit/o5O0Rr?p=preview.

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

Transform an unidentified function into a new type using TypeScript

Consider the following code snippet: type T = (x: number) => boolean; let fn = function(a: string, b: boolean, c: T){}; fn('yes', true, ()=> { }); Unfortunately, this code will not compile. The goal is to cast the anonymous function to ...

Error: The Kfold cross-validation function in Python can only convert arrays of length-1 to Python scalars

Attempting to implement Kfold cross validation for my model, but encountering an error in the process. Despite converting the length input to an array to accommodate KFold's requirement for 1D arrays, the error persists. from sklearn.ensemble import ...

Leveraging the angular-in-memory-web-api in conjunction with Angular CLI

Encountering some frustrating issues while trying to integrate angular-in-memory-web-api into my Angular 2 project that was built using Angular CLI. Here's the current structure of dependencies inside my package.json: "dependencies": { "@angular/co ...

Tips for ensuring the correct function type in TypeScript

TypeScript Version 3.5.1 Playground I've encountered an issue with TypeScript where the compiler fails to flag missing arguments in function declarations. Here's a basic illustration of the problem. interface IArgs { foo: number; } type MyF ...

The ngx-datatable encountered a resolution issue with its dependency tree and was unable to resolve it

I've been trying to incorporate ngx-datatables into an Angular 12 project by running the command npm install @swimlane/ngx-datatable. However, after installation, I encountered the following Errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to r ...

What is the best approach to develop a React Component Library adorned with Tailwind CSS and enable the main project to easily customize its theme settings?

Currently, I am in the process of developing an internal component library that utilizes Tailwind for styling. However, a question has arisen regarding how the consuming project can incorporate its own unique styles to these components. Although I have th ...

Generate a custom string to reference a JSON object containing a variable from an Angular HTML document

I am trying to generate a string within my HTML file to access data from a JSON object. HTML File <app-banner></app-banner> <section id="mail-view" class="bg-gray" > <div class="container"> <figure id="state-stats" class= ...

RXJS - Implementing a conditional logic in the switchMap operator to determine if it's the first

In my service's http fetch method, there is a parameter called "showLoadingSpinner". When this parameter is set to false, the HttpContext DISABLE_LOADER_FOR_REQUEST = true will be set. I would like to set showLoadingSpinner to false for every subsequ ...

Exploring the synergy between Visual Studio 2015 and Angular2 Beta 2's dependency injection functionality

Currently, I am using VS2015 alongside TypeScript 1.7.3 and Angular2 Beta 2 with a target of ECMA 5. In order to enable experimental decorators in my project, I have made modifications to the csproj file by including TypeScriptExperimentalDecorators = true ...

Can you please explain the process of implementing server-side rendering with React?

During my work, I utilized Node's express for sever side rendering with React. However, an unexpected error occurred as shown below. ^ SyntaxError: Unexpected token '<' This particular error popped up unexpectedly. I reached ou ...

Issue with Angular RxJs BehaviorSubject not updating correctly

I've encountered an issue while attempting to share a string value between sibling components (light-switch and navbar). The problem lies in the fact that the property themeColor fails to update when I emit a new value from my DataService. Below is t ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Adding an external JavaScript file to an Angular 5.0.0 project

Struggling to integrate hello.js into my Angular 5.0.2 project. See the CLI version below https://i.sstatic.net/RcGz5.jpg I have included the script file in angular-cli.json. "scripts": [ "./js/hello.js", "./js/hello.polyfill.js", ...

Secure Angular Applications on Azure using Content Security Policy Nonce

Seeking assistance here after not getting much response on ServerFault. I need help implementing a nonce for our CSP header policy. My goal is to eliminate "unsafe-inline" from the script-src policy by binding a nonce for angular's inline scripts. How ...

creating an m-member combination within an array of size n

Given an array with n members and another number, m, (m <= n) which is user-input. The task at hand is to generate all possible combinations of "m" members from the array. A[5] = {a,b,c,d,e}; B = 3 Number of combinations: C(5, 3) = 10 I am looking for ...

Differences Between Angular 2 CoreModule and SharedModule

Can anyone provide an explanation of the purpose of a SharedModule and a CoreModule? I've noticed that many projects are adopting this structure when building their Angular applications. What is the reasoning behind having two separate modules? At ...

What is the best way to transmit an i18n key from a parent component to a child component prior to beginning

When working with an input-field component that can be embedded in various parent components using forms, I encountered a challenge. Within the input child component, there is an i18n translation key variable using interpolation, which I aim to dynamicall ...

My issue lies in the subtraction of a quantity by using Object X from Array 1 and Object Y from Array 2

I am facing an issue with the function I'm using. It seems that when I attempt to do subtraction, both arrays are getting subtracted instead of just one. Here are the variables: let data1 = [ { ProductTotalId: 30, ProductId: 30, Quantity: 50 }, ...

Here's a method for transferring data from one array to another: when there is existing data in the

Although this may seem simple to some, I have been struggling with it for hours without any success. If I have the following data in an array: var tDataValues = { id: "TenantID", text: "FullName", username: "Username", cnic: 'CNIC&ap ...

Is it possible to bypass angular global styles without encapsulation? Try using either ViewEncapsulation.None or ::ng-deep

Is there a way to override global styles that are defined in the src/styles.scss file for a specific angular component? I have considered using ViewEncapsulation.None or ::ng-deep or /deep/ or >> , but each method seems to have its drawbacks. The us ...