简体   繁体   中英

How to bind statically defined HTMl content and click Event returned from java service to angular component

I am using angular 5 and java 8 for my web application. I am having a java service which return html content with angular click event. The same i am binding to angular component. The html content is working but click event is not working.

Below is the sample code from Java

@RequestMapping(value="/hitSample",method = RequestMethod.GET)
public String hitSample() {
    
    StringBuilder sb = new StringBuilder();
    sb.append("<a (click)=\"callSampleFunction()\"><p>This is a paragraph.</p>  A Tag end 
    </a>");
    sb.append("<p>This is a paragraph. 2 </p>");
    return sb.toString();
} 

SampleComponent.ts

import { Component, OnInit } from '@angular/core';
import {ViewReviewService} from '../../services/view-review-service';
import {Response} from '@angular/http';

@Component({
selector: 'app-sample-hit',
templateUrl: './sample-hit.component.html',
styleUrls: ['./sample-hit.component.css']
})
export class SampleHitComponent implements OnInit {
sampleData: any;
constructor(private viewReviewService: ViewReviewService) { }

ngOnInit() {

 this.hitSample();
}

hitSample() {
this.viewReviewService.hitSample().subscribe((res: Response) =>  {
  console.log(res['_body']);
  this.sampleData =  res['_body'];
  });
}
callSampleFunction() {
 alert('got call');
   }
 }

sampleComponent.html

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

I want callSampleFunction() to be triggered on click.

You can use the same way you've used <div [innerHTML]="sampleData" > </div> but you need to sanitise the string template for security reasons.

<div [innerHtml]="sampleData | safeHtml">

SafeHtmlPipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import DOMPurify from 'dompurify';

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): any {
     const sanitizedContent = DOMPurify.sanitize(value);
     return this.sanitizer.bypassSecurityTrustHtml(sanitizedContent);

  }
}

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