0

I have an existing directive that I'm trying to upgrade to angular 2. Basically, I don't want the consumer of this directive to be forced to change their html code.

<div ng-controller="MyCtrl">
  <textbox multiline></textbox>
  <textbox></textbox>
</div>

I have a jsfiddle here.

myApp.directive('textbox', function() {
  return {
    restrict:'E',
    template: "<div></div>",
    compile: function compile(tElement, tAttrs) {
    console.log(tAttrs.multiline, tAttrs );
      var textbox;
      if (tAttrs.hasOwnProperty("multiline")) {
        textbox = angular.element('<textarea></textarea>');
      } else {
        textbox = angular.element('<input type="text"/>');
      }
      tElement.append(textbox);
      return function(scope, iElement, iAttrs) {}
    }
  }
});

Inside the compile function, I'm using the existence of an attribute to determine what ultimately gets rendered. I can't find a recommended way to reproduce this functionality with Angular 2. Using the ElementRef seems like a code smell, but honestly given how sparse the documentation is for Renderer I'm unsure of how to proceed.

I have a working plunkr, but I don't like having to set up all the extra bindings for each of these properties I have on the element.

Please advise.

bodine
  • 1,763
  • 4
  • 19
  • 28
  • I don't get what the actual problem is. What are you trying to accomplish and where is the problem. I don't know what `compile` does in Ng1 (haven't used Nt1). – Günter Zöchbauer Apr 19 '16 at 13:41
  • @GünterZöchbauer, the compile function allowed me to have a single directive which could be used to render any of several different elements based on its attribute configuration. It seems if I want to keep my directive unchanged from my users' perspective, then I have to use ElementRef. I suppose the question is what is the right way of getting the functionality ported to angular 2. If not ElementRef, then what would work? Hope this helps, thanks. – bodine Apr 19 '16 at 15:39
  • Depends on what is known at build time. You could use `ngSwitch`, or `DynamicComponentLoader` – Günter Zöchbauer Apr 19 '16 at 15:40
  • @GünterZöchbauer, can I allow the use of standard/custom attributes, then in my constructor transform those into angular2's binding syntax? I used multiline here because it seemed simplest for the sake of the question, but I've got other attribute values that I need $parsed by angular. For example if I was using `my-model="vm.user.firstName"` how would that translate to angular2? – bodine Apr 19 '16 at 15:55
  • Usually templates need to be available statically otherwise Angular won't process them (no binding, no directive or component instantiation). http://stackoverflow.com/questions/36008476/how-to-realize-website-with-hundreds-of-pages-in-angular2 discusses a workaround but I would build on it because it's not officially supported and might cease to work eventually. – Günter Zöchbauer Apr 19 '16 at 16:01

0 Answers0