在Angular 2中解析HTML字符串并提取和更新值 [英] Parse HTML string in Angular 2 and extract and update values

查看:225
本文介绍了在Angular 2中解析HTML字符串并提取和更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始进行Angular项目,但有点卡住了.我有一个从(可信)外部源接收HTML字符串的组件.我想从此字符串中提取和更新值,并在我的组件中付清它.

I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

现在可以使用以下代码轻松显示字符串:

Now displaying the string is easily done with the following code:

<div [innerHTML]="displayString"></div>

我的输入字符串包含一些<span>元素,并附加了data-card-text元素作为标识符.是否可以提取该值,并在我的组件需要时更新它?

My input string has some <span> elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

示例: let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

这样的操作在Angular 2中是否可行?

Are operations like these even possible in Angular 2?

推荐答案

您必须创建一个共享服务,其中所有全局变量的定义如下.您的全局变量是" displayString "

You have to create one Shared Service in which all your global variables are defined like below. Your global variable is "displayString"

export interface SharedModel {
    displayString: string;
    dynamicValue: string;
}

@Injectable()
export class Shared {
    SharedComponent: SharedModel = {
           dynamicValue:'',
           displayString: '<svg><text data-card-text>'+this.SharedComponent.dynamicValue+'</text></svg>'
    };
}

现在在您需要以下设置/获取 displayString 的组件中访问此服务.

Now access this service in your component where you need to set/get displayString as below.

import { Shared, SharedModel } from '../Shared';
export class MyComponent {
     public sharedData: SharedModel;
     constructor(public sharedResource: Shared)
     {
         this.sharedData = sharedResource.SharedComponent;
     }
}

分配值:(在您的情况下,可能在其他组件/服务/APi中)

Assign Value:(it may be in other component/service/APi in your case)

ngOnInit()
{
     this.sharedData.dynamicValue="My name is SANDIP PATEL"
}

HTML中的

访问/获取值:

<div [innerHTML]="sharedData.displayString"></div>

这篇关于在Angular 2中解析HTML字符串并提取和更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆