lacolaco / ng-dynamic

dynamic contents projection in Angular

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Applying directives to elements within dynamic content

jeremyjrpugh opened this issue · comments

I am trying to apply a directive to an element that is part of a dynamically inserted content. My directive works fine for static content in a component but is not getting applied when the same element is added dynamically. Specifically I am trying to intercept "href" attributes and handle them so I don't reload or leave my angular app, but trigger a route instead.

Following the demo code, I've added an anchor to the static and dynamic html. My directive simply echos the href link to the console, which it does for the static element but not for the dynamic one.

Any ideas how to work round this?

Here's my update demo code:

`import { Component, OnInit } from '@angular/core';

@component({
selector: 'dynamic-cmp-demo',
template: <h2>dynamic-cmp-demo</h2> <a href="#/foo/bar">Some anchor</a> <div *dynamicComponent="content; context: {text: text};"></div> <awesome-button msg="static">Static HTML</awesome-button> <hr/> text: <input type="text" [(ngModel)]="text" /><br/> <textarea [(ngModel)]="content" rows="10" cols="50"></textarea>,
})
export class DynamicCmpDemoComponent implements OnInit {
content: string;

text = 'foo';

ngOnInit() {
fetchAwesomeDocument().then(content => {
this.content = content;
});
}
}

export function fetchAwesomeDocument() {
return Promise.resolve(`


Awesome Document



{{text}}


Dynamic anchor
Dynamic HTML

</div>
`); } `

The directive is simple enough:

import { Directive, Input } from '@angular/core';

@directive ({
selector: '[href]',
host: {
'(click)' : 'preventDefault($event)'
}
})
export class HrefDirective {
@input() href: any;
preventDefault(event: any) {
console.log('intercepted href click ', this.href);
event.preventDefault();
}
}

Thanks for you help

perhaps you can try it in this way:

  1. insert a special string(eg:'myLink') to the tag, eg: '<p myLink href="http://google.com" >Test link</p>'
  2. customize a component, temp named like 'MyComponent', and its selector can be any string, in this component you can do anything you want, such as: change the appearance of the original tag, or change the behavior of original tag;
  3. finally register the component to DynamicHTMLModule like this(of course you should import the component to the app module):
    DynamicHTMLModule.forRoot({ components: [ { component: MyComponent, selector: '[myLink]' }, ] })

any question can be emailed to me: gzhuzi@126.com