W
W
webivan12016-07-25 20:30:57
JavaScript
webivan1, 2016-07-25 20:30:57

How to initialize router in Angular2?

Good afternoon!
There is a certain page that receives json from the server in the form:

{
  h1: "Страница",
  seotext: "<p>Привет мир! <a href='/' [routerLink]=\"['MainPage']\">Я ссылка</a></p>"
}

I receive json and display data on the page through [innerHtml]
Of course, the link
<a href="/" [routerLink]="['MainPage']">Я ссылка</a>
does not work through angular2 how to make angular look at html and eat its directives again?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Zuev, 2016-07-26
@webivan1

Update
Updated version here Angular 2 how to set template dynamically?
You can try making a wrapper directive that will dynamically load a component with a template from your html.

import {
  Component,
  Directive,
  Input,
  ComponentFactory,
  ComponentMetadata,
  ComponentResolver,
  ReflectiveInjector,
  ViewContainerRef
} from '@angular/core';

function createComponentFactory(resolver: ComponentResolver, 
           metadata: ComponentMetadata): Promise<ComponentFactory<any>> {
  const cmp = class DynamicComponent { };
  const decoratedCmp = Component(metadata)(cmp);
  
  return resolver.resolveComponent(decoratedCmp);
}

@Directive({
  selector: 'html-outlet'
})
export class HtmlOutlet {
  @Input() html: string;

  constructor(private vcRef: ViewContainerRef, private resolver: ComponentResolver) {}

  ngOnChanges() {
    if (!this.html) return;

    const metadata = new ComponentMetadata({
      selector: 'dynamic-html',
      template: this.html,
    });

    createComponentFactory(this.resolver, metadata)
      .then(factory => {
        const inj = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.vcRef.createComponent(factory, 0, inj, []);
      });
  }
}

And then use this directive in the right place:
You can see the full example on plunkr

W
webivan1, 2016-07-26
@webivan1

Very cool, thanks!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question