As seen in this plunker, I'm dynamically adding an HTML to one of my elements, which boils down to this:
@Component({
selector: 'my-comp',
template: `<span [innerHTML]="link"></span>`,
}) export class MyComponent {
private linkContent = '<a routerLink="/my-route">GoTo Route</a>';
private link;
constructor(sanitizer: DomSanitizer) {
this.link = sanitizer.bypassSecurityTrustHtml(linkContent);
}
}
This results in <a routerLink="/my-route">GoTo Route</a>
being added to the DOM, but Angular knows nothing about the routerLink
directive on this element, and does not "bind" to it. So, when you click the link, it results in complete reload with re-bootstrap (which doesn't work in plunk, it just gives a 404).
Question: how to tell angular to go through the DOM (or its part, or even a single element) and perform component initialization if needed?
What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.
In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.
Angular2 doesn't process HTML added dynamically in any way except sanitization.
Passing '<a routerLink="/my-route">GoTo Route</a>'
to innerHTML
is doing exactly this, passing this string to the DOM, but nothing else. There is no routerLink
directive being instantiated or applied.
If you need to add HTML dynamically that uses Angular2 bindings, directives, or components, you can add the HTML to a components template, and add this component dynamically using ViewContainerRef.createComponent()
like demonstrated for example in Angular 2 dynamic tabs with user-click chosen components
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With