简体   繁体   中英

Angular 2+ jQuery dynamically add routerLink to html

I have a json object, which I want to show on the page with highlighting, folding etc. ngx-json-viewer allows rendering json with formatting, folding etc. In this json, there are certain values which I want to convert to hyperlinks. I am trying to dynamically add routerLink to these values.

I am able to use jQuery modify the json after it is rendered and add anchors like so:

main.find('.segment-key').each(function() {
  const key = $(this).html();
  if(key == replacement.key) {
    main.find('.segment-value').each(function() {
      let value = $(this).html();
      if(!_.startsWith(value, '<a')) {
        value = _.replace(value, '"', '');
        $(this).wrapInner(`<a href="${replacement.anchor}` + value + '" />');
      }
    });
  }
});

The anchors cause the page to refresh. I would like to replace the anchors with routerLink.

Any help would be greatly appreciated.

Thanks

PS: For anyone interested, I got this behaviour by adding a click event and handling the navigation in the controller:

main.find('.segment-key').each(function() {
  const key = $(this).html();
  if(key == replacement.key) {
    main.find('.segment-value').each(function() {
      let value = $(this).text();
      value = _.replace(value, new RegExp('\"','g'), '');
      if(!$(this).hasClass('hyperlink')) {
        $(this).addClass('hyperlink');
        $(this).on('click', function() {
          self.router.navigate([replacement.page, replacement.param + '/' + value]);
        });
      }
    });
  }
});

You don't need jquery to dynamise your view. Standart Angular component can handle that.

Moreover, I strongly recommand you to avoid using JQuery with Angular. Anything triggered by JQuery is out of Angular's sight. This said, you'll have to enter in a way more complexe implementation.

You'd better manipulate your DOM with tools provided by Angular itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM