Angular2 with Material Design Lite

2019-06-25 09:40发布

问题:

I have added the following bit of code in my angular2 app to help MDL re-register the components when moving around the app...

ngAfterViewInit() {
    componentHandler.upgradeDom();
}

And although it seems to be working ok (as expected) I am getting the following error...

(16,5): error TS2304: Cannot find name 'componentHandler'.

I'm still quite new to angular2 and typescript but I guess I need to import something so my code knows what componentHandler is(even though it must know what it is because it works and doesn't work without this code??? confused)

回答1:

It should help you to add

declare var componentHandler: any;

at the top of your code. Please refer to the corresponding handbook section on Working with Other JavaScript Libraries in TypeScript.



回答2:

if you are using cli.angular tool for generating your app do this, so that no need to duplicate the code everywhere.

  1. add below line into typings.d.ts file

       declare var componentHandler: any;  
  2. reference the file into your component file as below

       /// <reference path="../typings.d.ts" />  


回答3:

I guess you need to add

declare componentHandler;
componentHandler.upgradeDom();

See also Calling JavaScript directly from TypeScript