Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5+ components - using binding inside of templateUrl function

I'm using Angular 1.5+ with Typescript, preparing my code to be compatible with Angular 2. I've got a situation where many of my components need to use an application-wide repository location for the views that are mapped to their templateUrl properties, but sometimes a view needs a specific, local implementation.

So, normally the views are hosted on a fast-served CDN, they're re-used between multiple sites that all belong to the same general code base, api, etc. This is done to prevent duplicating them and to centralize what doesn't need to be repeated.

Rarely, I'll need to override this behavior and use a more specific, fine-tuned view. So my approach to this was to add a binding to the components called viewLocation, with the intent to use it like this;

<component-name></component-name> is the default. In this situation, the default CDN path is used. <component-name view-location="local"></component-name> is a unique situation. If this happens, the templateUrl should be able to respond to that and switch to a path relative to the specific application and not from the CDN.

I thought it would be pretty simple until I realized that I wouldn't have access to the binding properties within the actual constructor or templateUrl function, as is demonstrated here;

export class SidebarComponent extends Component {
   constructor() {
      super();
      this.bindings = { viewLocation: '=' };
      // other properties
      this.templateUrl = ($someService: IServiceInterface): string => {
         // help! I don't have access to the viewLocation property!
      }
   }
}

So is there anything else I can do to get access to that property?

like image 210
Ciel Avatar asked Mar 11 '23 19:03

Ciel


1 Answers

This is not done in TS, but the AngularJS 1.5 component generally provides the $element and $attrs to the $injector when you are using an injectable template.

This is an example in AngularJS using Javascript where the template URL is picked based on an attribute set on the component:

angular.module('example', []);

angular.module('example').component('myComponent', {
  templateUrl: function($element, $attrs, $log) {

    $log.info('determining template to be used');

    if($attrs.useTemplate) {
      return $attrs.useTemplate;
    }

    return 'default.html';
  }
});

Template snippet:

<my-component use-template="hui.html"></my-component>
<my-component use-template="bu.html"></my-component>
<p></p>
<my-component></my-component>

Working example: template injection in an angular 1.5 component

like image 125
simsibimsiwimsi Avatar answered May 04 '23 11:05

simsibimsiwimsi