Executing the ngIf directive in Angular 2 when a function or click event occurs

Is there a way to display an element only when a specific function is executed or a particular click event occurs? Here's the html code snippet I'm currently working with:

<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [mapTypeId]="maptype" [mapTypeControlOptions]="mapTypeControlOptions">
    <sebm-google-image-map-type [mapLayerId]="'linz'" [options]=imageMapOptions>
        <sebm-google-map-marker *ngFor="#location of locations" [latitude]="location.lat" [longitude]="location.lng" [label]="location.id" (markerClick)="updateDiv()">
            <sebm-google-map-info-window [disableAutoPan]="true"> {{ location.id }} <strong>{{ location.content }}</strong></sebm-google-map-info-window>
        </sebm-google-map-marker>
    </sebm-google-image-map-type>
</sebm-google-map>


<section  *ngIf="markerClick==true" id="ethiopian-desert">TEST</section>

I attempted using markerClick to achieve this functionality, but it doesn't seem to be functioning as expected. My goal is to display the element when a marker is clicked and hide it when the user clicks outside the element.

Check out the plunker example here

Answer №1

To display or hide a section based on the state value, you need to create and update a state accordingly. I have provided an example where the section will be shown when clicking on the marker and hidden when clicking on the map.

Example in your template :

  template: `
  <sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" (click)="hideSection($event)">
    <sebm-google-image-map-type [mapLayerId]="'linz'" [options]=imageMapOptions>
        <sebm-google-map-marker *ngFor="#location of locations" [latitude]="location.lat" [longitude]="location.lng" [label]="location.id" (markerClick)="showSection()">
            <sebm-google-map-info-window [disableAutoPan]="true"> {{ location.id }} <strong>{{ location.content }}</strong></sebm-google-map-info-window>
        </sebm-google-map-marker>
    </sebm-google-image-map-type>
</sebm-google-map>

  <section *ngIf="shouldDisplaySection" id="ethiopian-desert">TEST</section>
`

In your component :

  hideSection($event) {
    // stop event propagation on children
    $event.stopPropagation();

    this.shouldDisplaySection = false;
  }

  showSection() {
    this.shouldDisplaySection = true;
  }

You can view the updated plunker here: http://plnkr.co/edit/baF1WH1Dxp4eBAGpyHK6?p=preview

Answer №2

If you want to show and hide a section based on a click event, you can use the *ngIf directive in Angular by binding it to a boolean property that you toggle on click.

(markerClick)="updateDiv()"
<section *ngIf="isClicked" id="ethiopian-desert">TEST</section>

Within your component or App class:

updateDiv() {
    this.isClicked = true;
}

You can see an example of this functionality in action on this plunkr.

To hide the div, you simply need to re-toggle the this.isClicked boolean property with another click event on the top-level element:

<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" (click)="hideDiv()">

App class method for hiding the div:

hideDiv() {
    this.isClicked = false;
}

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

Error: The `ngMetadataName` property cannot be accessed because it is undefined or null in Internet Explorer version 10

Encountered an issue in IE 10 that is not present in IE 11: Error: TypeError: Unable to get property 'ngMetadataName' of undefined or null reference The property ngMetadataName can be found in the file vendor.js. This is the content of polyf ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

Conduct surveillance on the service function call within the constructor

I am currently facing a challenge with trying to monitor a service function call that is executed in the constructor. The test is straightforward, simply aiming to confirm that the function call is indeed made. beforeEach(async(() => { TestBed.con ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

When attempting to update a document using the PUT method in the MEAN stack, no changes are being applied

My application is designed to perform CRUD operations, it's very simple. I'm trying to update the information of a book but it's not working. What should I change? Additionally, I'm encountering this error: core.js:6210 ERROR TypeError ...

The element 'mdb-navbar-brand' in Angular is unrecognized and not known

Encountered this error while working on an Angular project. I'm at a loss on what steps to take next. Can anyone provide assistance? SCRIPT5022: Template parse errors: 'mdb-navbar-brand' is not a known element: 1. If 'mdb-navbar-brand& ...

Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows: ///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' /> ///<reference path='d.ts/DefinitelyTyp ...

Error: Unexpected character < in node_modules/angular2/ts/package.json syntax

I am currently working on developing an app with Angular 2 and have encountered an error during setup. The error message I received is: SyntaxError: /home/mts/Desktop/sampleProject/appSails/node_modules/angular2/ts/package.json: Unexpected token < at O ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

The system encountered an issue: Unhandled error: TypeError - the variable "users" has not been defined

I encountered an issue within this Component that is not being detected by the command prompt. Dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { User } from './user.component'; import { UserService ...

Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together. For example: myHouse => my_House aRandomString => a_Random_String And so on... T ...

Unable to display grid items in React material-ui grid list

export interface FlatsGridProps { flats: IClusterFlats[]; } export const FlatsGrid: React.StatelessComponent<FlatsGridProps> = (props: FlatsGridProps) => { if (props.flats.length === 0) { return (<div> empty </di ...

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

Differences between `typings install` and `@types` installation

Currently, I am in the process of learning how to integrate Angular into an MVC web server. For guidance, I am referring to this tutorial: After some research and noticing a warning from npm, I learned that typings install is no longer used. Instead, it ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

"Strange Type Conversion Behavior in next.js 13: Why is res.json() Converting Numbers to Strings

I have encountered a strange issue where no matter what I do, the fetched data is being partially converted to strings. For example, the 'bialko' and 'kcal' fields are supposed to be of type Float in Prisma, yet they are getting casted ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

Creating a custom type for the parameter of an arrow function in Typescript

I need assistance defining the type for an object parameter in an arrow function in TypeScript. I am new to TypeScript and have not been able to find any examples illustrating this scenario. Here is my code: const audioElem = Array.from(videoElem.pare ...

What is the best way to enforce input requirements in Typescript?

I am currently facing an issue with two required inputs that need to be filled in order to enable the "Add" button functionality. I have considered using *ngIf to control the visibility of the button based on input values, but it seems to not be working. ...