Angular5如何传递包含函数调用的html标记字符串?

时间:2019-01-12 10:40:13

标签: html5 angular5

我在component.ts中生成了HTML,该HTML嵌入了对函数调用的使用,如下所示:

<a (click)='showProfileDialog("<b>TEST</b>")'>Click Me</a><br>

如果我将其硬编码到component.html中,则一切正常。但是,相反,我想在component.ts中生成HTML,就像我在功能getProfileAnchor()

中所做的那样

我需要做一些编码吗?如果您查看component.html,您会看到我正在将包含生成的HTML的viewHtml传递到safeurl函数中。似乎就足够了。

component.html

<div id="content" data-sparkline-container="" data-easy-pie-chart-container="">
  <div class="row">
    <sa-big-breadcrumbs [items]="['Forum', 'Post View']" icon="comment" class="col-xs-12 col-sm-7 col-md-7 col-lg-4"></sa-big-breadcrumbs>
    <sa-stats></sa-stats>
  </div>
  <div class="row">
    <div class="col-sm-12">
      <div class="well">
          <div [innerHTML]="viewHtml | safeurl: 'html'"> </div>  

<!-- THIS WORKS IF UNCOMMENTED                        
          <a (click)='showProfileDialog("<b>TEST</b>")'>Click Me</a><br>
-->              
          <hr width="10%" size="8" align="center">
          <br><br>
          <table class="table table-striped table-forum"><tbody>
              <tr>
                <td>
                  <h4><strong>Post a Reply</strong></h4>
                  <i id="forumPost" [summernote]="{height: 180}" (change)="savePostContent($event)"></i>

                  <button (click)="postTheContent()" class="btn btn-primary margin-top-10 mybtn" style="font-weight: 800">
                    Post
                  </button>
                  <button (click)="previewTheContent()" class="btn btn-success margin-top-10 mybtn" style="background-color: green">
                    Preview
                  </button>
                </td>
              <tr>
          </tbody></table>
      </div>
    </div>
  </div>
</div>

component.ts

import { NgModule, Component, OnInit, Injectable, Pipe, PipeTransform, ViewChild } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { FadeInTop } from "../../../shared/animations/fade-in-top.decorator";
import { ExDialog } from '../../../shared/dialogs/ex-dialog.service';
import { ActivatedRoute } from '@angular/router';

import { AuthService } from '../../../+auth/auth.service';
import { DialogService } from '../../../shared/dialogs/dialog.service';
import { ForumService } from '../forum.service';

declare let $:any;

@FadeInTop()
@Component({
  selector: 'sa-post-view',
  templateUrl: './post-view.component.html',
  styleUrls: ['../../../../assets/css/tmd_basic.css']
})

@Injectable()  
export class PostViewComponent implements OnInit {

  public initialContent = "Add text here";
  public postContent: any;

  public topicList: any;
  public topicSubjList: any;
  public postList: any;
  public publicProfileList: any;
  public attachmentList: any;

  public postID: string;
  public groupName: string;
  public topicName: string;
  public topicSubj: string;

  public viewHtml: any;

  constructor(
    private forumService: ForumService,
    private dialogService: DialogService,
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private exDialog: ExDialog
  ) {
  }

  ngOnInit() {
    this.getTopicList();
    this.getTopicSubjList();
    this.getPostList();
    this.getPublicProfileList();
    this.getAttachmentList();

    this.activatedRoute.queryParams.subscribe(params => {
        this.postID = params['postID'];
        if(!this.postID) {
          this.groupName = "Discussions";
          this.topicName = "TangleMyData";
          this.topicSubj = "Welcome Message";
          this.postID="14"; 
        }
        //###console.log("PostViewComponent ngOnInit - this.postID: " +this.postID);
      });

    this.getForumData();

    this.viewHtml = this.getViewHtml();
  }

  showProfileDialog(profileStr: string) {
    //###console.log("PostViewComponent showProfileDialog - profileStr: " +profileStr);
    this.dialogService.htmlDalogWidth = "40%";
    this.exDialog.openSimpleDialog("custom", profileStr, "Public Profile");
  }

  getViewHtml(): any {
    //###console.log("PostViewComponent getViewHtml - ENTRY");

    let result = `  
      <table class="table table-striped table-forum">
        <thead>
        <tr>
          <th colspan="2"> ` +this.getHeadAnchor() +` </th>
        </tr>
        </thead>
      `;

    result += `<tbody>`;

    let creatorName: string;
    let creationDate: string
    let publicProfile: any;
    let attachment: any;
    let attachmentCnt: number;
    let postContent: string;
    let postAttachments: string;

    for(const groupRow of this.topicList) {
      if((groupRow.groupName === this.groupName) && (groupRow.topicName === this.topicName)) {
        //###console.log("PostViewComponent getViewHtml - groupRow.groupName: " +groupRow.groupName +"; this.groupName: " +this.groupName +"; groupRow.topicName: " +groupRow.topicName +"; this.topicName: " +this.topicName);
        const groupID = groupRow.forumID;
        console.log("PostViewComponent getViewHtml - groupID: " +groupID);

        //get all posts for the topic - the order of posts are by their dateCreated; the results from the DB must be ordered correctly
        for(const postRow of this.postList) {
          if((postRow.forumID === this.postID) || (postRow.parentID === this.postID)) {
            creatorName = postRow.posterName;
            creationDate = postRow.dateCreated;
            postContent = postRow.postContent;
            //###console.log("PostViewComponent getViewHtml - creatorName: " +creatorName +"; postContent: " +postContent);

            //get public profile
            for(const searchRow of this.publicProfileList) {
              if(searchRow.personID === postRow.posterID) {
                publicProfile = searchRow;
                //###console.log("PostViewComponent getViewHtml - publicProfile.personID: " +publicProfile.personID);
                break;
              }
            }

            //get post attachments
            //###console.log("PostViewComponent getViewHtml - topicRow.forumID: " +topicRow.forumID);
            for(const searchRow of this.attachmentList) {
              if(searchRow.forumID === postRow.forumID) {
                attachment = searchRow;
                //###console.log("PostViewComponent getViewHtml - ############## attachment.forumID: " +attachment.forumID);
                break;
              }
            }

            //create post attachment section
            if(attachment) {                     
              //get attachment count
              attachmentCnt = 0;
              //###console.log("PostViewComponent getViewHtml - ########## attachment: " +attachment);
              if(attachment && attachment.attachments) {
                attachmentCnt = attachment.attachments.length;
              }
              //###console.log("PostViewComponent getViewHtml - attachmentCnt: " +attachmentCnt);  

              //start attachment <ul> tag                      
              const downloadAllAnchor = this.getDownloadAllAnchor(attachment.attachments);

              postAttachments = `
                <div class="forum-attachment"> `
                  +attachmentCnt +` attachment(s) &#124; ` +downloadAllAnchor +`
                  <ul class="list-inline margin-top-10">`;

              //create <li> tags
              let liTags = ``;
              for(const item of attachment.attachments) {
                liTags += `
                  <li class="well well-sm padding-5">
                    <strong>` +item.fileName +`</strong>
                    <br>`
                      +item.fileSize +`
                    <br>`
                      +this.getDownloadAnchor(item) +` | ` +this.getViewerAnchor(item) +`
                  </li>`
              } 

              //end attachment <ul> tag 
              postAttachments += liTags +`
                  </ul>
                </div>`;
            } else {
              postAttachments = ``;
            }

            result += this.getHtmlRow(postContent, creatorName, creationDate, publicProfile, postAttachments);
          }
        } //postList loop
      }
    }

    result += `</tbody></table>`;

    return result;
  }

  getHeadAnchor(): string {
    //###console.log("PostViewComponent getHeadAnchor - ENTRY");

    const headGenHrefURL = "#/app-views/forum/general-view?groupName=" +encodeURIComponent(this.groupName);
    const headTopicHrefURL = "#/app-views/forum/topic-view?groupName=" +encodeURIComponent(this.groupName) +"&topicName=" +encodeURIComponent(this.topicName);
    //###console.log("PostViewComponent getHeadAnchor - headHrefURL: " +headHrefURL);

    return '<a href=' +headGenHrefURL +'> ' +decodeURIComponent(this.groupName) +'</a> &gt; <a href=' +headTopicHrefURL +'> ' +decodeURIComponent(this.topicName) +'</a> &gt; ' +decodeURIComponent(this.topicSubj);   
  }

  getProfileAnchor(publicProfile: any): string {
    //###console.log("PostViewComponent getProfileAnchor - ENTRY");

    return `<a (click)='showProfileDialog("<b>TEST</b>")'>Click Me</a><br>`;
  }

  getHtmlRow(postContent: string, creatorName: string, creationDate: string, publicProfile: any, postAttachments: string): any {
    //###console.log("PostViewComponent getHtmlRow - ENTRY");

    const result = ` 
          <tr>
            <td class="text-center" style="width: 12%;">
              ` +this.getProfileAnchor(publicProfile) +`
              <small>` +publicProfile.postCnt +` Posts</small>
            </td>

            <td>
              <strong>` +creatorName +`</strong> on <em>` +creationDate +`</em>
              <br><br>`     
                 +postContent +` `
                 +postAttachments +`
            </td>
          </tr>
    `;

    return result;
  }
}

component.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SmartadminLayoutModule } from "../../../shared/layout/layout.module";
import { StatsModule } from "../../../shared/stats/stats.module";
import { SummernoteDirective } from '../../../shared/forms/editors/summernote.directive';
import { SmartadminModule } from '../../../shared/smartadmin.module';
import { TMDSharesModule } from '../../../shared/tmd_shares/tmdshares.module';
import { FormsModule } from '@angular/forms';
import { PostViewRoutingModule } from './post-view-routing.module';
import { PostViewComponent } from './post-view.component';
import { TooltipModule } from 'ngx-bootstrap';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    SmartadminModule,
    SmartadminLayoutModule,
    StatsModule,
    TooltipModule,

    PostViewRoutingModule,
    TMDSharesModule
  ],
  declarations: [
    PostViewComponent,
    SummernoteDirective
  ],
  exports: [
    SummernoteDirective
  ]
})

export class PostViewModule {
}

感谢您为解决此问题提供的帮助。我想在多个地方使用这种技术。

谢谢, 鲍勃

0 个答案:

没有答案