【问题标题】:Routing in array Angular 5阵列Angular 5中的路由
【发布时间】:2018-09-07 16:50:02
【问题描述】:

我有一个动态内容的字符串数组,我需要在其中为段落和链接添加路由和 HTML 标记。我似乎无法为这种路由或 HTML 的使用找到正确的术语。我错过了什么?

例子-

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

@Component({
 selector: 'app-new',
 templateUrl: './new.component.html',
 styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit  {
new: object[];

constructor(private router: Router) {


this.new =  [
    {
      newtitle: "This is my title",
      newcontent: "Lorem ipsum dolor sit amet, <a (click)="newLink()">consectetuer</a> adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.<br>Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat."
    }
]

}

【问题讨论】:

  • 您能说明一下您想要完成的工作吗?您是否想在您的组件模板中动态显示 HTML,其中包含指向应用程序其余部分的 routerLinks?您提供的有限代码确实无助于演示您要做什么。
  • 是的,我正在处理大量动态文本。在大部分动态文本中都有链接,一些是内部的,一些是外部的。这些链接目前只要直接输入到 component.html 页面就可以工作,但是,如果它们在数组文本中,它们就不能工作。
  • 您将需要使用动态组件。本文将帮助您入门:blog.angularindepth.com/…
  • 非常感谢!

标签: arrays string angular dynamic routing


【解决方案1】:

我假设您正在尝试在 new.component.html 中显示新内容。以下是你可以做到的:

在 new.component.html 中:

<div [innerHtml]="new.newcontent | keepHtml: 'html'"></div>

创建一个新的管道 safe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';


@Pipe({ name: 'keepHtml', pure: false })
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}

public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
    case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
    case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
    case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
    case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
    case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
    default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
}
}
}

注意:不要忘记将管道添加到您的应用模块。

【讨论】:

  • 添加换行符和基本标签非常有用。我仍然无法获得工作链接,课程也不起作用?
  • @RyanIndustries8 当然,此解决方案仅适用于非常基本和简单的 HTML。如果您的 html 具有任何级别的复杂性(例如路由器链接),那么您将需要使用动态组件来创建必要的模板。如果我不得不猜测,这就是它被否决的原因,因为这个解决方案对您的用例没有任何作用。
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 2018-08-10
  • 1970-01-01
  • 2023-03-27
  • 2018-04-23
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多