Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove html tags from text in angular 2

I am working with rss feed and got rss feed from my server so i am sending stringfy data but when i bind this in my angular 2 application it shows text with html tags so how we can remove this tags. I just want to show text only.

Here is server code:

exports.newspage=function(req,resp){
db.executeSql("select header,text,teaser from news_d",function(data,err){
        if(err){
            resp.writeHead(200,{"Content-Type":"text/html"});
            resp.write("<html><head><title>500</title></head></html>");
        }
        else{
            resp.writeHead(200,{"Content-Type":"x-application/json"});
            resp.write(JSON.stringify(data));
        }
        resp.end();
    });
};

app.get('/newspage', function(req, resp) {

    emp.newspage(req,resp);

});

service.ts:

gettagesnews(){
     let headers = new Headers();
       headers.append('x-access-token',this.token);
         var options = new RequestOptions({headers: headers});
      return this.http.get('http://services.com:9000/newspage/',options).map((res:Response) => res.json())
    .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

news.ts:

tagesnews:Array<TagesnewsList>;

this.newsauth.gettagesnews().subscribe((dailynews)=>{
    this.tagesnews=dailynews;
  });

html:

<div *ngFor="let daily of tagesnews">
       <span style="font-size: 13px">{{daily.text}}</span> </button>
    </div>

i got response with some like this:

sample text

like image 941
U rock Avatar asked Mar 21 '17 14:03

U rock


3 Answers

You just need to bind html:

<div *ngFor="let daily of tagesnews">
   <span style="font-size: 13px" [innerHTML]="daily.text"></span>
</div>
like image 51
Igor Janković Avatar answered Oct 07 '22 17:10

Igor Janković


There are two ways to handle it.

1) use the innerHTML tag in your html file like this =

<div>
      <pre [innerHTML]="description"></pre>
</div>

here, description is field which hold the data with html tags(<div>hi<br></br></div>)

2) Second way is that convert your html tags data in plain string then bind with respective form control.

like :- formData['description'] = formData['description'].replace(/<[^>]*>/g, '');

like image 39
nagender pratap chauhan Avatar answered Oct 07 '22 18:10

nagender pratap chauhan


All of the [innerHTML] answers have the content of the HTML actually rendered... so images are loaded, etc. well if you don't want that, and just the text... you can use a conversion method like this:

stripHtml(html: string) {
    var div = document.createElement("DIV");

    div.innerHTML = html;

    let cleanText = div.innerText;

    div = null; // prevent mem leaks

    return cleanText;
}
like image 45
Serj Sagan Avatar answered Oct 07 '22 16:10

Serj Sagan