2

I am wondering how to use the DirectiveResolver object to alter a given Component.

Dependencies (ng2 moves so fast these days things become obsolete quickly)

"@angular/common": "~2.4.3",
"@angular/compiler": "~2.4.3",
"@angular/core": "~2.4.3",

I have tried this:

import { Component } from '@wwwalkerrun/nativescript-ngx-magic';
import { OnInit, Directive, Type } from '@angular/core';
import { DirectiveResolver } from '@angular/compiler';


class myViewResolver extends DirectiveResolver {
    resolve(type: Type<any>, throwIfNotFound?: boolean): Directive {        
        var view = super.resolve(type, throwIfNotFound);
        console.log(type);
        console.log(view);
        return view;
    }
}

@Component({
  selector: 'app-root',
  templateUrl: 'views/app/app.component.html',
  styleUrls: ['views/app/app.component.css'],
  providers: [myViewResolver]
})
export class AppComponent {
  title = 'app works!';
}

But I don't get the logs so I suspect the resolver is not executed.

Any idea?

ps: no entry in the official angular.io api documentation...

Sebas
  • 21,192
  • 9
  • 55
  • 109

1 Answers1

3

You need to pass extra providers by bootstrapping application to override default compiler providers.

So i think this should work:

platformBrowserDynamic().bootstrapModule(AppModule, { 
  providers: [
    { provide: DirectiveResolver, useClass: myViewResolver } 
  ]
});

Plunker Example

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • @yurzui: Do you know, if one is able to override `templateUrl`s also in this fashion? The `view` that ends up in the `DirectiveResolver` already seems to have a fetched template its `template` property ... – Volker Rose Aug 02 '17 at 09:56
  • 1
    @VolkerRose Do you mean like this https://plnkr.co/edit/IOWpMZDzR3Kjiie0zfKA?p=preview ? – yurzui Aug 02 '17 at 10:03
  • @yurzu: Exactly, thanks a ton. I will check why my approach did not work locally respectively compare it with your Plunkr. When it works I would be happy to document it in a separate question here on SO and you can answer it :) – Volker Rose Aug 02 '17 at 11:08
  • Hmm. Might be a version thing, my app is on `2.4.6`. – Volker Rose Aug 02 '17 at 11:19
  • @VolkerRose https://plnkr.co/edit/VhE3FcyxrqBZk6uvS8ot?p=preview How do you build your application? webpack? – yurzui Aug 02 '17 at 11:21
  • Yeah, it's build via webpack and the version is irrelevant, I also tried it with https://plnkr.co/edit/mkGGwrr1uQtF0KPswXtk. – Volker Rose Aug 02 '17 at 11:27
  • @VolkerRose It means that your webpack configuration uses loader that replaces `templateUrl` with `template` For example angular-cli https://github.com/angular/angular-cli/blob/master/packages/%40ngtools/webpack/src/loader.ts#L351-L354 – yurzui Aug 02 '17 at 11:39