Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then disappears as it sets to display: none.

In order to close the modal, there is a close button within the child component. The problem is that I have only been able to achieve this by using display: none in the CSS, which makes the component invisible but still operational.

My ultimate goal is to find a way to completely unload the child component when the close button is pressed, or to set opacity: 1 if the parent image is clicked again.

HTML Structure:

<app-image-modal
    *ngIf="clicked"
    [slice] = "slice"
    [clicked] = "clicked">
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

Typescript (TS) for Parent Component:

export class ImageComponent {
public clicked = false;

public imageClicked() {
    this.clicked = true;
}
}

Child Component HTML:

<section [ngClass]="{'hide': hide}">
  <div [ngClass]="{'active': show}">

    <img src"img.png" />

    <div class="close" (click)="hideModal()">
        <button>X</button>
    </div>

  </div>                                                              
</section>

TS Child Component:

export class ImageModalComponent implements OnInit {
public show = false;
public hide = false;

@Input() clicked: boolean;

public ngOnInit() {
    this.show = true;
}

public hideModal() {
    this.show = false;
    this.hide = true;
}
}

Answer №1

Your component communication seems to be in the wrong direction.

When it comes to closing, information should flow from child to parent. One way to achieve this is by using an EventEmitter in your child component and then listening for it in the Parent component.

If you need to unload the child component, you can utilize a boolean variable along with an *ngIf directive in the parent's template to control when the child component is displayed.

The responsibility of showing or hiding the modal should be handled at the parent level (eliminating the need for separate show and hide booleans in the child component, possibly reducing it to just one boolean).

Why handle this at the parent level? Because you want to actually unload the component, not simply hide it.

Here is a code example:

** In the child component ** :

export class ImageModalComponent implements OnInit {
    @Output() close = new EventEmitter();

    public hideModal() {
        this.close.emit(); // notifying the parent that the "close" button has been clicked.
    }
}

In the child's HTML, remove any references to "show" and "hide" (assuming the component is always visible):

<section>
  <div class="active">
  ...

** In the parent template : **

export class ImageComponent {

    public clicked = false;

    public imageClicked() {
        this.clicked = true;
    }

    public childCloseEventHandler(): void {
        this.clicked = false; // setting this will trigger unloading of the child component as per `*ngIf="clicked"` on the child component
    }
}

Parent HTML:

<app-image-modal
    *ngIf="clicked"
    [slice]="slice"
    (close)="childCloseEventHandler()">   <!-- Updated line -->
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

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

Issue encountered with the inability to successfully subscribe to the LoggedIn Observable

After successfully logging in using a service in Angular, I am encountering an error while trying to hide the signin and signup links. The error message can be seen in this screenshot: https://i.stack.imgur.com/WcRYm.png Below is my service code snippet: ...

Analyzing a string using an alternative character

I want to convert the string "451:45" into a proper number. The desired output is 451.45. Any help would be appreciated! ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

The index type '{id:number, name:string}' is not compatible for use

I am attempting to generate mock data using a custom model type that I have created. Model export class CategoryModel { /** * Properties */ public id : number; public name : string; /** * Getters */ get Id():number{ return this.id; ...

Revising input value post model binding

In my scenario, I have a text input that is bound to a model property of type Date: <input type="text" [(ngModel)]="model.DateStart" ngControl="dateStart" id="dateStart" #dateStart /> The value of model.DateStart (which is of type DateTime) looks l ...

What strategies can I employ to manage browser compatibility issues while utilizing contemporary JS and CSS frameworks?

I have been working on a project that utilizes the most recent versions of Angular (version 5) and Bootstrap (4). However, after a few weeks of development, I noticed that some features are not functioning properly on Safari, and I am uncertain if all fea ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

Encountered a problem while attempting to create a new project using angular/cli

I'm brand new to npm and Angular 2, and I'm attempting to set up a fresh Angular 2 project using angular/cli. My current setup includes: Node v8.9.3 npm v5.6.0 Windows 10 To start, I executed npm install -g @angular/cli successfully. Next, I n ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

Leveraging the power of mat-option and mat-radio-button within a mat-select or mat-selection-list

I'm currently working on a unique form element that combines checkboxes and radio buttons to create a multi-level selection feature. For instance, you can use it to configure properties for a car where a radio option (Digital or FM) is dependent on t ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

Issue: StaticInjectorError(DynamicTestModule)[CityService -> Http]: Http provider not found

I am working on a service that retrieves all cities from a web service. @Injectable() export class CityService { constructor(private http: Http, private router: Router, private auth: AuthService) { } public getAllCity(): Observable<City[]> { ...

Issue with starting Angular2 beta 15 using npm command

I am encountering a problem when trying to launch the quick start application for Angular2. node -v 5.10.1 npm -v 3.8.6 My operating system is EL CAPTAIN on MAC OS X. This is my tsconfig.json file: { "compilerOptions": { "target": "es5", "mo ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Exploring Angular2's DOMContentLoaded Event and Lifecycle Hook

Currently, I am utilizing Angular 2 (TS) and in need of some assistance: constructor(public element:ElementRef){} ngOnInit(){ this.DOMready() } DOMready() { if (this.element) { let testPosition = this.elemen ...

Tips for implementing a guard feature using a modal window

I am looking to implement a dialog window with yes and no responses when clicking on a router link. If the user selects 'yes', I want to pass through the canActivate guard. The issue arises when returning to the same router with the guard in pla ...

I thought enabling CORS would solve the issue, but it seems like the restrictions

This is my setup for an asp.net core web API: public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...