Angular 2: access to injected decorator dependencies

I am making a reusable Angular2 component, and I want the user to be able to specify a template string or templateUrl, which the component will use either by attribute or by setting it through some maintenance method.

In Angular 1, it's simple, we can do something like this:

// somewhere else in app
myService.setTemplateUrl('path/to/template.html');

// directive definition
function myDirective(myService) {

  return {
    template: function(element, attrs) {
      return attrs.templateUrl || myService.getTemplateUrl();
    }
    // ...
  };

}

How is this achieved in Angular2?

@Component({
  selector: 'my-component',
  template: '...' // cannot see `mySerivce` from here, nor access the element attributes
})
export class MyComponent {

  constructor(private myService: MyService) {}

}

While my problem is how to implement a dynamic template, the broader question is whether it is possible to access injected dependency instances from various decorators.

+4
source share
2 answers

So, I finally figured out a way to do what I wanted using custom templates.

, , . Angular 2.

, , :

SimpleTimer, :

<!-- app.ts template -->
<div *simpleTimer="#timer=timerApi">
  <div class="time">{{ timer.getTime() }}</div>
  <div class="controls">
    <button (click)="timer.toggle()">Toggle</button>
    <button (click)="timer.reset()">Reset</button>
  </div>
</div>

TemplateRef ViewContainerRef :

// SimpleTimer.ts
constructor(private templateRef: TemplateRef,
          private viewContainer: ViewContainerRef,
          private cdr: ChangeDetectorRef) {}

ngOnInit() {
  // we need to detach the change detector initially, to prevent a
  // "changed after checked" error.
  this.cdr.detach();
}

ngAfterViewInit() {
  let view = this.viewContainer.createEmbeddedView(this.templateRef);
  let api = {
    toggle: () => this.toggle(),
    reset: () => this.reset(),
    getTime: () => this.getTime()
  }
  view.setLocal('timerApi', api);

  setTimeout(() => this.cdr.reattach());
}

, , . , .

+3

: , - DI. , . , , .

, , , . , , EASY.

3 :

1.Use * ng-if

, , . , , .

<special *ngIf="!type">Default</special>
<special *ngIf="type == 'awesome'"> I'm Awesome </special>
<special *ngIf="type == 'admin'">Admin Only</special>

: . : , ,

2. DynamicComponentLoader

. . , .

, ,

.. ,

- 100% (Super hacky, messes with asyncRouter)

: "Angular" , . : , . , , .

3. Cheat ( Angular) javascript. , window, self encapsulated

template: (function() {
    return "<supertemplate-" + window.superTempId + "' />";
}())

( ) , ,

: WHEN.. , , , - ,

: , : Angular. .

, , - " " .

, !

+1

Source: https://habr.com/ru/post/1620510/


All Articles