简体   繁体   English

Angular 2+ jQuery动态将routerLink添加到html

[英]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. 我有一个json对象,我想在页面上以突出显示,折叠等方式显示。ngx-json-viewer允许以格式化,折叠等方式呈现json。在此json中,有些值我想转换为超链接。 I am trying to dynamically add routerLink to these values. 我正在尝试将routerLink动态添加到这些值。

I am able to use jQuery modify the json after it is rendered and add anchors like so: 我能够使用jQuery在呈现后修改json并添加锚点,如下所示:

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. 我想用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: PS:对于任何有兴趣的人,我都会通过添加click事件并在控制器中处理导航来获得此行为:

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. 您不需要jquery来动态化您的视图。 Standart Angular component can handle that. Standart Angular组件可以处理此问题。

Moreover, I strongly recommand you to avoid using JQuery with Angular. 此外,我强烈建议您避免将jQuery与Angular一起使用。 Anything triggered by JQuery is out of Angular's sight. jQuery触发的任何事情都不在Angular的视线范围内。 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. 您最好使用Angular本身提供的工具来操作DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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