I aim to link a variable in a directive with a component

Each directive comes with its own functionality and specific features. It can be challenging to understand how to connect a variable from a directive to a component. This particular directive involves detecting x-axis and y-axis positions during mouse events, as well as utilizing a boolean variable called movable.

// Modules and Components
import { Directive, Input, ElementRef, HostBinding, HostListener } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

// Directive
import { DraggableDirective } from '../draggable/draggable.directive';

// Interfaces
import { Position } from '../../../../interfaces/draggable-system/move-position';

/**
 * Enables the movement of objects.
 */

@Directive({
  selector: '[appMovable]'
})
export class MovableDirective extends DraggableDirective {

  // ********** DECLARATIONS **********//

  // Overview of the Inputs, Outputs, and HostBindings
  @Input('appMovable') set movable(movable: boolean) {
    this.enabled = movable;
  }

  @HostBinding('class.moving') moving = false;

  // Check the positions
  position: Position = { x: 0, y: 0 };
  private startPosition: Position;
  private reset = false;

  constructor(
    public element: ElementRef,
    private sanitizer: DomSanitizer) {
    super();
  }

  // Utilize HostBindings and HostListener

  @HostBinding('style.transform') get transform(): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle(
      `translateX(${this.position.x}px) translateY(${this.position.y}px)`
    );
  }

  @HostListener('dragStart', ['$event']) onDragStart(event: PointerEvent): void {
    this.moving = true;
    this.startPosition = {
      x: event.clientX - this.position.x,
      y: event.clientY - this.position.y
    };
  }

  @HostListener('dragMove', ['$event']) onDragMove(event: PointerEvent): void {
    this.position = {
      x: event.clientX - this.startPosition.x,
      y: event.clientY - this.startPosition.y,
    };
  }

  @HostListener('dragEnd') onDragEnd(): void {
    this.moving = false;

    if (this.reset) {
      this.position = {
        x: 0,
        y: 0,
      };
    }
  }
}

Answer №1

Export your directive like this

@Directive({
  selector: '[appMovable]',
  exportAs: 'appMovable'
})

By using a template reference variable, you can specify the "exportAs" value and utilize it (you can even call a function if desired)

<div appMovable #d="appMovable">{{d.movable}}</div>

Answer №2

Here are a couple of solutions to consider:

1) Utilize a service to store a global variable that gets updated when MovableDirective is called. To do this, make sure to inject your service into your Directive.

2) Another option is to use @Output in your directive to pass the movable data up to your Component.

export class MovableDirective extends DraggableDirective {
[...]
@Output()
eventToBubbleUp = new EventEmitter<boolean>();
[...]
onDragEnd() {
    [...]
    this.eventToBubbleUp.emit(movable);
}
}

To implement this, you can use the following code:

<div [...] appMovable (eventToBubbleUp)="toDo(movable)"></div > 

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

Verify whether the user is authenticated in Angular 2

For the past couple of days, I've been struggling with figuring out how to determine if a user is authenticated in my Angular-rc1 application and could really use some assistance or guidance. After receiving a token from the server, I want to save it ...

``I'm facing an issue with Ionic 4's npm run build --prod command not functioning properly when deploying

Embarking on my first project with Ionic 4, I have previously worked with Ionic 3 where I used to build for the web using the command: npm run build --prod However, when attempting to build the Ionic 4 project with the same command, it generates an exces ...

Determine the specific data types of the component properties in React Storybook using TypeScript

Currently, I am putting together a component in the storybook and this is how it appears: import React, { useCallback } from 'react'; import { ButtonProps } from './types'; const Button = (props: ButtonProps) => { // Extract the nec ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

ng serve in Angular 6 may cause compatibility issues with HttpClientModule and mat-icons

After implementing basic unit tests with Jest, I encountered an issue where my mat-icons were not displaying correctly and my HttpClient calls to the backend were returning empty responses when running the Angular app with "ng serve." Despite subscribing t ...

Share information by including the provider within the @component declaration in Angular

I am looking to explore a new method of passing data using providers directly within the component itself. For instance, I am curious if there is a way to pass a variable from one component to another without relying on routing or other traditional methods ...

Displaying the component that was provided as a parameter

I am looking to develop a custom component that can take another component as a parameter and then embed it within an NgBootstrap modal while also incorporating additional HTML elements. I am unsure if this is achievable, but my goal is to enhance modals ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

Encountering an issue with d3 Angular 2 pie chart related to d3.arc data

I encountered a problem with my code: 'PieArcDatum' is not assignable to parameter of type 'DefaultArcObject.' at this specific line Argument of type return "translate(" + labelArc.centroid(d) + ")";. Could someone please assist me in ...

When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value. const arrayDays = Array.from(Array(32).keys(), (num) =& ...

Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu. Currently, all items have a ...

Angular project facing issues during Maven build process

Hi there, I'm currently facing some challenges while trying to deploy my Angular and Spring Boot application. Whenever I run the command mvn clean compile spring-boot:run, I encounter a build failure from my Angular pom file. The error message I am r ...

Exploring the fruitful synergy of Node.js, Mongoose and MongoDB in Typescript for powerful MapReduce operations using the emit() function

Currently, I am experimenting with a side project using the MEAN stack and Typescript. I have encountered an issue where Typescript is not recognizing the typings for the emit() and Array.sum() methods. See my code snippet below... let options: mongoose. ...

Prevent the Mat Dialog from showing up depending on the situation

I am attempting to prevent a Mat Dialog from appearing unless a specific condition is met. I originally thought about using Angular Guard, but since there is no associated route with the component (besides the main webpage it's called from), that appr ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

The combination of the table, thead, and tbody components causes disruptions in the layout of the overall table structure

After creating separate components for table, thead, and tbody and then assembling them on a parent page, the table ends up breaking completely. I'm at a loss on how to resolve this issue. This is the table component: <table> <ng-conte ...