How to detect async change to ng-content

后端 未结 2 348
孤城傲影
孤城傲影 2020-12-11 05:37

I made a component which uses the marked package to render markdown content, the thing is it doesn\'t re-render itself when an async event changes its n

相关标签:
2条回答
  • 2020-12-11 05:54

    Adding an @Input() content; and using the component like

    <markdown [content]="info"></markdown>
    

    would make this easier.

    Alternatively a MutationObserver should work well for this specific use case.

    0 讨论(0)
  • 2020-12-11 05:55

    Even if the Günter's answer is great, I wasn't able to resist to create a little plunkr describing how to use Marked into a component: https://plnkr.co/edit/0oSeaIyMWoq5fAKKlJLA?p=preview.

    Here are the details:

    • Marked configuration the HTML file

      <script>
        System.config({
          transpiler: 'typescript', 
          typescriptOptions: { emitDecoratorMetadata: true }, 
          packages: {
            'src': {defaultExtension: 'ts'}
          },
          map: {
            marked: 'https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.js'
          }
        });
        System.import('src/boot')
          .then(null, console.error.bind(console));
      </script>
      
    • The component that uses Marked

      import { Component, Input } from 'angular2/core';
      import marked from 'marked';
      
      @Component({
        selector: 'markdown', 
        template: `
          <div [innerHTML]="convertedData"></div>
        `
      })
      export class MarkdownComponent {
        @Input('data')
        data:string;
      
        ngOnChanges() { 
          this.convertedData = marked(this.data);
        }
      }
      
    • The component that uses the previous Markdown component

      import { Component } from 'angular2/core';
      import { MarkdownComponent } from './markdown';
      
      @Component({
        selector: 'my-app', 
        template: `
          <div>
            <markdown [data]="markdown"></markdown>
          </div>
        `,
        directives: [ MarkdownComponent ]
      })
      export class AppComponent {
        constructor() {
          this.markdown = 'Hello';
      
          setTimeout(() => {
            this.markdown = `
      # Title
      
      Some __test__
      `;
          }, 1000);
        }
      }
      
    0 讨论(0)
提交回复
热议问题