alanhe421 / angular-demo

ng5
7 stars 2 forks source link

showdownjs,实现MD格式进行HTML渲染 #52

Open alanhe421 opened 6 years ago

alanhe421 commented 6 years ago

最新实现md博客写作平台,需要实现MD格式渲染,这里记录下实现

使用类库:showdownjs

alanhe421 commented 6 years ago
  1. CDN资源引入

    <script src="https://cdn.bootcss.com/mark.js/8.11.1/mark.min.js"></script>

    如果不想CDN引用在CLI配置文件中加入scripts配置也可。

  2. markdown全局设定 因为我想全局使用一个markdown设定,所以在APP根组件中进行设定,如果不想全局,直接在对应组件中设定即可

    
    declare let showdown: any;

export class AppComponent { constructor() { showdown.setFlavor('github'); showdown.setOption('openLinksInNewWindow', true); }

}

3. 组件使用
```typescript
declare let showdown: any;
export class EditComponent implements OnInit, OnDestroy {
  renderedCnt: string;
  sourceCnt: string;
  converter = new showdown.Converter();
  updateView() {
    this.renderedCnt = this.converter.makeHtml(this.sourceCnt);
  }
<div class="row">
  <div class="col-md-6">
    <textarea class="form-control sourceCnt" [(ngModel)]="sourceCnt"
              (ngModelChange)="updateView()">
    </textarea>
  </div>
  <div class="col-md-6">
    <div id="rendered" [innerHtml]="renderedCnt|safe" class="rendered-post">

    </div>
  </div>
</div>

image