What is the alternative for using the compile function in angular 2 for this use case?

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>

I have a jsfiddle here.

myApp.directive('textbox', function() {
  return {
    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"/>');
      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.

Leave a Reply

Notify of