How to call a method defined in a directive applied on multiple components

Hi,
I need to call a method defined in a directive.
This directive is applied to several components on the same page.

home.html

<ion-content padding>
    <ion-item>
        <ion-label stacked>Input 1</ion-label>
        <ion-input #input1 item-content myDirective [(ngModel)]="data"></ion-input>
    </ion-item>
    <ion-item>
        <ion-label stacked>Input 2</ion-label>
        <ion-input #input2 item-content myDirective value="value2"></ion-input>
    </ion-item>
</ion-content>

home.ts

import { Component, ViewChild } from '@angular/core';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
    @ViewChild('input2') input2;
    data: any;
  constructor() {
        this.data = 'value1';
  }
    ngOnInit() {
        setTimeout(() => {
            this.data = 'value1 (modified)';        <= Change value through model
            this.input2.myMethod('value2 (modified)');  <= Call method defined in myDirective
        }, 4000);
    }
}

myDirective.ts

import { Directive, ElementRef
             } from '@angular/core';
@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
    constructor( private el: ElementRef ) {
    }
    public myMethod( myParam ) {
        ...
    }
}

When myMethod is called from home.ts, I get this error message:

_this.input2.myMethod is not a function

I thought that myDirective was injecting myMethod into the component on which it is applied, but it seems Iā€™m wrong.

How can I call myMethod on #input2 only, from home.ts?

1 Like