0

We have an existing plugin that we call like this

var result = $('.myElement').OurPluginName({});

I am trying to replace this with a Angular2 Directive.

My test.ts:

/// <reference path="test.d.ts" />
import { Directive, ElementRef, NgZone } from '@angular/core';

@Directive({
    selector: 'test'
})

export class Test {
    public ngAfterViewInit(): void {
        this.zone.runOutsideAngular(() => {
            this.OurPluginName({});
        });
    }
}

My test.d.ts:

declare function OurPluginName(options: Object): void;

Despite creating a declaration, it still is giving me an error:

Property 'OurPluginName' does not exist on type 'Test'.


SOLUTION: (thanks to Volodymyr Bilyachat)

test.ts:

/// <reference path="test.d.ts" />
import { Directive, ElementRef, NgZone } from '@angular/core';

@Directive({
    selector: 'test'
})

export class Test {
    public constructor(private elRef: ElementRef) {
    } 

    public ngAfterViewInit(): void {
        this.zone.runOutsideAngular(() => {
            $(this.elRef.nativeElement).OurPluginName({});
        });
    }
}

test.d.ts:

declare var $: any;

1 Answer 1

1

You are calling this.OurPluginName({}) which is not defined.

export class Test {
    public ngAfterViewInit(): void {
        this.zone.runOutsideAngular(() => {
            this.OurPluginName({}); <-- here you call for this
        });
    }
}

you should have something like this:

add type definition for $ since your plugin is jquery one

declare var $: any;

define in class method to call

export class Test {
  constructor() {

  }

  CallOurPluginName(options) {
    $('.myElement').OurPluginName({})
  }

  public ngAfterViewInit(): void {
    this.zone.runOutsideAngular(() => {
      this.CallOurPluginName({});
    });
  }
}

PS. Its not the best way but it should work.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Volodymir. But I was tyring to get rid of the jQuery selector and change it to a directive, so I now have <test></test>. Is it possible?
@Aximili well but you plugin is jquery plugin?
@Aximili its possible but you need to rewrite your plugin to be angular component. because var result = $('.myElement').OurPluginName({}); this telling me that you are using jquery
Sorry it takes an element, doesn't have to be jQuery. It can be $('.myElement')[0].OurPluginName({});
Sorry I was wrong please ignore my last comment, I got confused myself. You're right. Thank you Volodymyr!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.