Delete a particular instance of a component from an array within the parent component when a button is clicked within the child component, depending on a specific condition in Angular

One scenario I am facing involves the removal of a component instance from an array (located in the parent component) when a button is clicked inside the child component, based on a specific condition.

https://i.sstatic.net/YPFHx.png

Within the parent component, the 'Add BU' button is present, with three text fields below (named 'BU', 'G Value', and 'C Value') along with a close button, all of which are generated by the child component. Every time the 'Add BU' button is clicked, a new row from the child component is added to the UI. I have utilized the code below to push instances of the child component to an array in the parent component:

https://i.sstatic.net/kszYg.png

https://i.sstatic.net/glN0q.png

Now, I have two questions regarding the above setup: 1. How can I delete a specific child instance from the parent's array when the corresponding close button is clicked (which resides inside the child component)? 2. How can I retrieve the values entered in each text field (e.g. 'BU', 'G Value', and 'C Value') in each row upon clicking the 'Add' button?

Similar questions have been asked before, and I have implemented a strategy similar to the one provided in the accepted answer in this link: Add component to dom on click of button in angular2. My first question is also evident in the image below:

https://i.sstatic.net/TRhCG.png

Answer №1

If you want to remove a child instance, you can use the following code:

<payment-option
    *ngFor="let bu of buList; index as i"
    (delete)="removeBU(i)>
</payment-option>
removeBU(i: number) {
  this.buList.splice(i, 1);
}

For retrieving data on add, you can use this code snippet:

@ViewChildren(PaymentOptionComponent) paymentOptionComps!: QueryList<PaymentOptionComponent>;

add() {
  const data = {};
  this.paymentOptionComps.forEach(comp => {
    // Get data from comp and add it to data here.
  });
}

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

ng-bind-html is having trouble parsing the HTML correctly and binding it

Here is the code for my controller: myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) { $scope.table="<p>OOPSY</p>"; $sc ...

Unable to utilize the concatMap() method in conjunction with the angular2 Http feature

Looking to chain multiple http requests, the number of requests can vary and they are not dependent on the previous request's result. The goal is to only keep the returned object from the last request. Received two suggestions on this forum thread. T ...

How to assign multiple values within nested for loops in Angular 6

I am facing an issue with my template file where I have two loops. I am attempting to bind the second value using the first loop value, but I am encountering an error. <tr *ngFor="let splitdata of mf.data"> <td *ngFor="let slitup of searchFie ...

Display the designated element upon clicking the designated link exclusively

I'm working with this specific HTML setup: <a href="#" class="dp">Click me</a> <div class="dp_div" style="display: none;"> this is the content within the div </div> My goal is to display the hidden div with a class of "dp_ ...

Instructions for obtaining the most recent event using the `fromEvent` function

I'm having trouble capturing the final event generated by the keyup event using rxjs. Every time, my console is filled with multiple log messages. Here's the Angular directive I'm working with: import { Directive, AfterContentChecked, Eleme ...

Utilizing Angular to bind properties conditionally

Can a property be conditionally bound in an Angular template? For instance, if I have an Observable with some data <my-component *ngIf="input$ | async as input" [input1]="input.input1" [overrideValue]="input.ove ...

Which is the preferred choice for retrieving data using ngrx: Resolver or Guard?

Utilizing Angular along with ngrx, my goal is to navigate to a certain route and ensure that the necessary data is available in the ngrx/store. I am implementing a ngrx/store action/effect/reducer to make API calls. The component associated with the route ...

Challenges with rendering text in Three.js

We are currently working on a project in three.js and facing difficulties when it comes to loading fonts onto our text elements. Our approach involves using the TextGeometry object for rendering fonts and the typeface js converter to incorporate new fonts ...

The connection status of socket.io is always inactive

At this moment, here is what I have. There are three different attempts within the constructor comments. Currently, when the frontend launches, it continuously tries to connect with the backend in socket.io. The backend does receive the connection, but th ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

I am perplexed as to why my useEffect function is executing twice within my NextJs client

I am currently working on a NextJs program and using a function called useAsync on my website. However, I have noticed that this function runs twice every time it is called. I suspect that the useEffect calling the useAsyncInternal might be causing this be ...

Can you explain the significance of the syntax "require: ^"?

Can someone explain the significance of the ^ symbol under require in this Angular directive code snippet? I came across this code and am having trouble understanding its meaning. .directive('accordionGroupHeading', function() { return { ...

Fetching data from one component to load an Angular component

Essentially, I have a grid within Ionic that dynamically populates its rows using ngFor. Each row contains an ionic button labeled "View details" which, when clicked, should display all the data associated with that specific object. Imagine it as a preview ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...

Tips for resizing an image to perfectly fit on a compact HTML5 canvas without sacrificing its quality

I need assistance with my code. I'm trying to draw an image on the canvas while maintaining its quality. const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); canvas.width = 360px; canvas.height = 360px; const img ...

Unslider: Ensure images stay centered even on smaller screen resolutions

Utilizing Unslider in a recent project from . Managed to align the slider halfway, but facing an issue with off-center slides on resolutions of 1920px and lower. The image width is 3940px. Attempted to implement the code snippet from this answer like so: ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Issue with Jade not displaying external JSON data

I am struggling with a jade template that is supposed to display all possible solutions from the QPX Express search request: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'RwDOf6H ...

The errors in React-hook-form do not refresh or update as expected

I'm currently working on a form that features custom components. However, I'm facing an issue where the errors object fails to update when a field is invalid. Specifically, the onInvalid callback triggers successfully when the password field is i ...