Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the constructor works fine. Can anyone help me figure out how to use this with onclick? Your assistance is greatly appreciated.

Here's the code for the directive:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[Bluecolored]'
})
export class BluecoloredDirective {

  constructor(private element:ElementRef) {
    console.log(element);
   element.nativeElement.style.color = "blue";
   }

clicked(){
  this.element.nativeElement.style.marginLeft = 20;
  console.log("marzi" + this.element.nativeElement.style.marginLeft);
}
}

And here's the template that uses the directive:

<p Bluecolored>
  new-fom works!
</p>
<h1 Bluecolored>Blue Colored</h1>
<button   (click)="clicked()" Bluecolored>Click</button>

Answer №1

An alternative approach to achieve the desired functionality in your directive is by utilizing a HostListener:

@HostListener('click') myClick(){
    this.element.nativeElement.style.marginLeft = 20;
    console.log("The margin-left value is now: " + this.element.nativeElement.style.marginLeft);
}

With this implementation, you can eliminate the need to include (click)="clicked()" on the button.

In my example, I've named the event listener function as 'myClick', but feel free to use any other relevant name that suits your preference.

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

Utilize jQuery to choose a specific tab

I have implemented a jquery tab in my UI. I want to have the second tab selected when the page loads, instead of defaulting to the tab with the "Active" class. Here is my HTML tab code: <div class="typo"> <div class="container-fluid"> ...

The TypeScript namespace does not exist or cannot be located

Currently, I am working on coding in TypeScript. The specific code pertains to an Angular 2 application, but the main focus of my inquiry lies within TypeScript itself. Within my project, there are certain files that contain various models, such as the exa ...

How can I move a complete range of values up using the Google Sheets API in Node.JS?

I'm working with a Google Spreadsheet that is being accessed and modified by a Node.JS app. There's a specific situation where I need to shift an entire range up (moving A3:D up by one cell), but due to my limited experience with the Google Shee ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

Navigate the conversation within the dialog without affecting the content below

Is it possible to have a dialog with scrollable content on top of a page that is also scrollable, but when trying to scroll inside the dialog using the mouse wheel, only the dialog body scrolls and not the page below it? What approach can be used to accom ...

Suggestions for incrementing a button's ID every time it is clicked

I am working on a button functionality that increases the button id when clicked. Below is the HTML code for the button: <input type="button" id="repeataddon-1" name="repeataddon" class="repeataddon" value="add" > Accompanied by the following scr ...

Incorporating external API information into Google Maps

My current challenge involves creating a polygon on Google Maps using data obtained from an external API found at . Upon analyzing the API response, the following information is provided: { "id": 28, "name": "Local spots", "description": "", "isprivate": ...

Tips for eliminating the border surrounding the entire table in Material-ui

Is there a way to edit a table in Material-ui without displaying it as a card? I'm looking to remove the border around the entire table, but I couldn't find any information on how to do that. Can someone help me out? Here is a link about the com ...

Tips for using jQuery to dynamically apply CSS styles to new content added to a webpage

I have encountered this question multiple times on stackoverflow and through google search, but unfortunately none of the suggested solutions have worked for me. My issue involves a page that loads an HTML page with empty sections, which are then dynamica ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

Error: The property 'parentNode' cannot be read because it is null

I wanted to test if my laptop can handle WebGL by loading examples from my instructor's webpage. The examples on the webpage worked fine, just showing a square within a square. I then decided to copy the exact codes into a notepad text editor, saved t ...

"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript: // inquiry.ts ...

Customize the color of a specific day in the MUI DatePicker

Has anyone successfully added events to the MUI DatePicker? Or does anyone know how to change the background color of a selected day, maybe even add a birthday event to the selected day? https://i.stack.imgur.com/or5mhm.png https://i.stack.imgur.com/so6Bu ...

What is the proper way to utilize the name, ref, and defaultValue parameters in a select-option element in React Meteor?

I recently developed a Meteor project using ReactJS. I have a Create/Edit page where I use the same input field for various form elements. Here is an example of code snippet that I currently have: <FormGroup> <ControlLabel>Province</Control ...

Troubleshooting custom fonts not displaying on a .NET website: Importing fonts for web use

https://i.stack.imgur.com/uWSsY.pngI am well-versed in HTML, but my knowledge of VB.NET is limited. In standard CSS, including a font like the one below would typically work, but I have encountered issues when attempting to do so in .NET. @font-face { f ...

What steps can I take to address the div issue in my React application?

After implementing Browser Router, I am encountering whitespace on the left and right side of the navbar. How can I resolve this issue? Below is the code snippet: <div className="container my-3"> <BrowserRouter> ...

Steps to incorporate / insert Angular directive in an application

In my app, the main.js file is located in the root folder. -app |_ routes.js |_ main.js -components |_directives |_abc-directive.js I am trying to figure out how to define a directive that can be accessed from a different folder. This is what I at ...

Transforming all commas to plus signs in a JavaScript codebase for the entirety of

Currently, I am using winston for logging and have created a common method to log throughout the project. However, I am facing an issue with many logging statements that look like this: logger.info("here is the data" , data) The problem arises when trying ...

The term 'MapEditServiceConfig' is being incorrectly utilized as a value in this context, even though it is meant to refer to a type

Why am I receiving an error for MapEditServiceConfig, where it refers to a type? Also, what does MapEditServiceConfig {} represent as an interface, and what is the significance of these brackets? export interface MapEditServiceConfig extends AppCredenti ...

Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs s ...