2

Trying to route from html´s template to a component, I tried different approaches, but they are not working.

I can route between component, from html to a template or urlTemplate (setting it value in script´s tag). But I can´t link from a html to a component.

Here is the idea:

index.html

<a href="my_angular_component">My_something</a>

my_component.ts

@Component({
  selector: 'myComponent-list',
  template: `
    <h2>myComponents</h2>

    <ul>
      <li *ngFor="let myComponent of myComponents">
        {{myComponent.name}}
      </li>
    </ul>
  `,
  directives: [ROUTER_DIRECTIVES]
})

I tried the next approaches:

Using routes´s component and [routerLink] attribute:

routes.ts

export const MyComponentAppRoutes = [
  { path: 'myComponent', component: my_component },
]

index.html

<a [routerLink]="['/myComponent']">My_something</a>

Not working, because I can´t use routerLink in html, directly.

Another one, definying route provider directly from html by script:

<script>
        var app = angular.module("HelloWorld", ["ngRoute"]);
        app.config(function($routeProvider) {
            $routeProvider
                .when("/cartelera", {
-- HOW CAN CALL MY COMPONENT HERE? NOT TEMPLATE DIRECTLY BECAUSE I WANT TO INJECT A SERVICE.
-- NOT A URLTEMPLATE FOR THE SAME REASON.
                });
            });
        </script>

Finally, I defined a component called mylink, Just for using routeLink from the definition of itself, but, event it works, doesnt look correct. Have I to define a component for every link I have?

I can´t get it. :S

Thanks mates... :)

Kenzo_Gilead
  • 2,187
  • 9
  • 35
  • 60

1 Answers1

2

You can't. When this code is executed, Angular is not yet running.

You can assign a value to window.someName and then from within the component read window.someName.

If actually function($routeProvider) { ... } is called after Angular and your component is initialized, you can assign a method of your component to window.someName and than from your script tag call window.someName(someParam)

See also Angular2 - how to call component function from outside the app

Another approach would be an event

From your script method

var event = new Event('my-event');
// or
var event = new CustomEvent('my-event', {'detail': someData});
window.dispatchEvent(event);

and in your Angular component

@HostListener('window:my-event', ['$event'])
myEventHandler(event) {
  console.log(event);
  // or
  console.log(event.detail);
}

See also https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567