How to Remove Components, Form Elements, and Items using NgIf in Angular?

Is there a way to remove DOM elements and Components using *NgIf or any Ng function?

I am working with a dropdown list that displays different forms based on the selection. The issue arises when a user changes the dropdown option, returns to the original option, and finds that the previous form data still exists instead of being cleared.

What would be the most effective method to delete all forms, variables, and the component itself when the dropdown selection changes?

Refer to the code snippet below,

<div class = "addressformtotal">
    <div class = "addressblock">
        <app-address-formatheader-form></app-address-formatheader-form>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('Standard')"><app-address-mailing-standard-form></app-address-mailing-standard-form></div>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('Military')"><app-address-mailing-military-form></app-address-mailing-military-form></div>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('Post')"><app-address-mailing-pobox-form></app-address-mailing-pobox-form></div>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('Free')"><app-address-free-form></app-address-free-form></div>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('Rural')"><app-address-mailing-rural-form></app-address-mailing-rural-form></div>
        <div *ngIf="formatMessage?.addressFormatDescription.includes('International')"><app-address-mailing-international-form></app-address-mailing-international-form></div>
    </div>

Answer №1

In my opinion, the inner components (app-address-mailing-standard-form, app-address-mailing-military-form...) could benefit from having an @Input for formGroup and *ngIf directives.

@Input()group:FormGroup

<form *ngIf="group" [formGroup]="group">
    <input formControlName="prop1">
     ...
</form>

Therefore, your main.app could look like this:

<app-address-formatheader-form 
         [group]="form.get("header")>
</app-address-formatheader-form>
<app-address-mailing-standard-form 
         [group]="form.get('mailing')">
</app-address-mailing-standard-form>
<app-address-mailing-standard-form 
         [group]="form.get('military')">
</app-address-mailing-standard-form>
...

If you create the form in your main.app as shown below:

this.form=new FormGroup({
   header:new FormGroup({...}),
   military:new FormGroup({...})
})

Only "header" and "military" will be displayed, but this is just a suggestion. It all depends on how and where you create the form and formGroup.

If you create the formGroup within the components, you can use a setter in the input like this:

@Input() set visible(value)
{
    if (visible)
       this.group=new formGroup({...})
}

And pass only the "visible" argument:

<app-address-formatheader-form [visible]="variable"></app-address-formatheader-form>

Once again, the form should include:

<form *ngIf="group" [formGroup]="group">
    <input formControlName="prop1">
     ...
</form>

Answer №2

One approach is to utilize reactive forms for the ability to reset a form easily. This method does not involve two-way binding, allowing for better control over your data.

When there is a change in the dropdown selection, ngIf can be used to generate a new reactive form with no pre-existing data.

To learn more about creating reactive forms, visit this link.

From my understanding, the issue may arise from binding data shared between components (parent-child) causing changes through two-way binding without effecting any actual alterations.

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

Conceal Reveal Secret Script

Can you help me with a question regarding the spoiler on this specific page? Here is the link: When I click on Windows, a table appears. However, when I click on Linux, the content of Windows disappears. I am looking to create a spoiler like this, but whe ...

Calculating numbers with Math.ceil will result in an increase of 1

After using Math.ceil, one value was rounded up to 50 and the other to 80. However, when I added these two values together, the result unexpectedly turned out to be 131. console.log(Math.ceil(e.currentTarget.clientHeight) // 50 console.log(Math.ceil(e.cu ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

Align Divs Horizontally to Center

I'm trying to find a way to horizontally center multiple DIVs in a straight line. Here's how my code currently looks: HTML: <div id="circle"> <div id="circle1"></div> <div id="circle2"></div> </div> CSS ...

Creating personalized features on Three.js models: Geometry's custom attributes

I have been grappling with an issue while using Three.js. I am trying to pass a custom attribute to my shader, which needs frequent updates. The shader is set as a ShaderMaterial for my mesh. However, the problem I am facing is that Three.js has recently ...

Issues with include and exclude directives in tsconfig.json are causing problems

I am currently working on a web project that involves organizing folders. Within my project structure, I have subfolders like the following: src/app/shared/models src/app/shared/services src/app/shared/types Each of these subfolders contains additional ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...

Error in Spring when updating with PATCH API in React JS due to missing request body

Spring exhibition - Error Resolved: Required request body is missing for updating delivery status Console error - Error: Request failed with status code 400 class UpdateOrder extends Component { state = { deliveryStatus:"" } handleCha ...

Overlapping dynamic content causing CSS nested scrollbars to clash at full width of 100%

Displayed below is a layout with two nested divs, both featuring automatic vertical scrolling. Is there a CSS technique available to show the inner scrollbar while maintaining the inner div at 100% width? https://i.stack.imgur.com/HSKHH.png div { ba ...

What is the best way to eliminate existing double quotation marks within string values stored in objects in Angular?

When using Angular, data is retrieved in object form from the database to the backend and then to the frontend. Here's how it looks in HTML: <h3>Payslip for the month of {{dataout[0].MonthYear | json }}</h3> The issue arises when running ...

Unable to properly test the functionality of the material-ui select component due to an error being thrown stating that the function is not being called

I've been utilizing the material-ui select component in my project and am currently writing tests for it. However, I've encountered an issue regarding testing the onChange event of the component. Here's a snippet of the code for my component ...

The input data from the MySQL database requires two page refreshes in order to be retrieved

Every time I input new values into the form fields and submit them, the page needs to be reloaded twice to display the updated values. For example, consider the $balance_2 in the 7th line. This line calculates the sum of all row values and updates the Bal ...

Looking to prevent horizontal scrolling on smartphones in an HTML webview - how can I do this?

Currently, I am dealing with a webview and encountering some peculiar behavior. The overflow-x property is set to hidden, which works perfectly on browsers. However, when accessed on a mobile device, the overflow seems to be ignored completely. Here is t ...

What is the best way to incorporate unique body CSS for various pages within a ReactJS application?

I am currently in the process of developing a multi-page website and faced with the challenge of applying different CSS styles to the body based on the specific page. My approach involves using react-router-dom for handling routing, and my file structure ...

"Chrome experiences issues with onmouseover functionality when navigating away from a page or posting content

I'm experiencing an issue with a page where I have onmouseover and onmouseout attributes set for pictures. When submitting, the onmouseover and onmouseout events cause the images to fail, resulting in the image source not found icon being displayed. ...

The button appears flawless in Chrome and Firefox, but unfortunately fails miserably in Internet Explorer. Is there any way to make it functional in all

Check out this JFiddle link: http://jsfiddle.net/Zfnz2/ I'm seeking ideas from the wise minds of the internet. Any thoughts? ...

D3 not distinguishing between bars with identical data even when a key function is implemented

When attempting to create a Bar chart with mouseover and mouseout events on the bars using scaleBand(), I encountered an issue. After reviewing the solution here, which explains how ordinal scale treats repeated values as the same, I added a key to the dat ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

Angular 8 encountered an error in content_script.js at line 71. The error was classified as a LEVEL: ERROR within the MODULE:

I am currently working on an Angular 8 application with Dotnet Core, and I have encountered a strange error message in the developer's console recently: content_script.js:71 LEVEL: ERROR | MODULE: LEAKED_CREDENTIALS | SESSION: a1293cfe | MESSAGE: &qu ...

Adjust the CSS border to finish at a 90-degree angle rather than a 45-degree angle

The div I'm working with has unique colors for the border-bottom and border-right properties, creating a diagonal line that separates the box at a 45 degree angle. I'm looking to adjust the bottom-border to be shorter in order for the right bord ...