Utilizing Angular: Invoking a function from a directive within a component

I'm attempting to invoke a method from a directive. Let's assume I have a directive myDirective.ts

@Directive({
  selector: '[something]',
})
export class myDirective implements OnInit {
....
public myMethod(){
console.log("it works")
}
....
}

and component.ts (this is what I found but on this.directive I get an error saying object is possibly null)

@Component({
  selector: '...',
  templateUrl: '....html',
  styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
  @ViewChild(myDirective) directive = null

  ngOnInit() {
  }

  onClickFunction() {
    return (
      this.directive.myMethod();
    );
  }
}

How can I effectively call this method in the component?

Answer №1

To execute, follow these steps

@Component({
  selector: '...',
  templateUrl: '....html',
  styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
  @ViewChild(myDirective) directive;

  ngOnInit() {
  }

  onClickFunction() {
    return (
      this.directive?.myMethod()
    );
  }
}

Include the following in tsconfig.json

"strictPropertyInitialization":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

Angular Component Encounters 401 Error Connecting to Youtube API

I've been working on a project in Angular that involves retrieving a list of YouTube videos using the YouTube API. Below is the service I've put together to handle this task. import { Injectable } from '@angular/core'; import { HttpClie ...

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...

Error handling in Angular is not properly managing the custom exception being thrown

I am currently working on an Angular 12 application and I have a requirement to implement a custom ErrorHandler for handling errors globally. When I receive an error notification from the backend, I subscribe to it in the ToolService using this.notificati ...

Retrieving the attribute key from a dynamically typed object

Having this specific interface structure: interface test { [key: string]: string } along with an object defined as follows: const obj: test ={ name: 'mda', telephone: '1234' } Attempting to utilize this object in a variab ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Developers beware: A functional component is generating a warning during development. Remember, function components do not support refs. Perhaps you intended to utilize React.forwardRef

Hey there! I have a question about a plugin that I've created and integrated into an application called HRnet (React 18). During development, I'm not encountering any warnings on the plugin side. However, when developing on the application side, ...

Implementing a back button in an RTL layout with Ionic 2

Just starting an Ionic 2 app in Arabic language requires a RTL layout. I decided to go with the side menu template. Adding the following line for configuring the app to RTL perfectly changed everything's direction, except for the back button which st ...

Create a compilation of categories/interfaces based on a mapping

Imagine you have the following object: const ROUTES = { PAGE_NO_PARAMS: '/hello/page/two', PAGE_R: '/about/:id', PAGE_Z: '/page/page/:param/:id', PAGE_N: '/who/:x/:y/:z/page', } as const Can we create a set ...

When attempting to compile my Angular project using the command ng build --prod, I encountered a server error stating that the document

Everything was running smoothly when I was working on my local machine, but once I uploaded the files generated from ng build --prod to the server, a problem arose. Now, whenever I try to route via a button in my components, an error appears. When I clic ...

Angular client encounters error "Access Control Check Fails for Preflight Request" when integrating with ASP.net Core SignalR

In my ASP.Net core server startup.cs file, I have the following code within the ConfigureServices method: services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder .AllowAnyMethod() .AllowAnyHeader() ...

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Exploring Angular Heroes: Encounter with a 404 Error in the in-memory-web-api Tutorial

I've been working on the Angular Tour of Heroes app and got to the HTTP section. Here is the link: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. All was going well until the tutorial instructed me to remove my mock service and replace it w ...

Problems encountered while starting npm in Angular 13

Versions -> PS C:\Users\user> npm --version 8.8.0 PS C:\Users\user> node --version v16.15.0 Executing the following command-> npx -p @angular/cli ng new JokeFrontB After that, I run Serve -> npm start and encountered t ...

Declaring a custom Angular Pipe

I've created a custom Pipe to filter a list of items and integrate it into my Angular/Ionic application. // pipes/my-custom-filter/my-custom-filter.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomFilt ...

Encountering the error message "Angular: invalid URL value sanitization" every time I attempt to refer to a folder within

I'm currently working on a project where I need to pull images from my disk into an Angular application using PHP as the backend for file retrieval. <ngb-carousel *ngIf="imageNames" class="carousel-fade"> ...

Creating custom designs for Material UI components

Although not a major issue, there is something that bothers me. I am currently using react, typescript, and css modules along with . The problem arises when styling material ui components as I find myself needing to use !important quite frequently. Is th ...

Is it time to end my MediaObserver subscription in flex-layout for Angular?

Within my Angular component, I have implemented the following code to display different elements based on screen resolution: constructor(private mediaObserver: MediaObserver) {} private mySubscription: Subscription; public ngOnInit(): void { this.my ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Troubleshooting a metadata issue while pre-compiling a feature module in Angular 2

Currently, I am in the process of developing an Angular2 library using Angular2 RC6. This particular library consists of a single module: import { Component, OnInit, NgModule } from '@angular/core'; import { CommonModule } from '@angular/c ...

Detecting changes in an ondrop event triggered by a modification in object property

As I work on creating a drag and drop interface, I realize the importance of implementing change detection for smooth functionality. Below is a snippet of my component: import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; impor ...