简体   繁体   中英

How can I render a template from a string in Angular 8+?

I would like to write a blog system where the writers can insert some custom angular components into their posts like this:

<p><b>Please solve this task!</b></p>
<task question="How much is 2+4?" answer="6"></task>

So the task component would display the question, and an input tag to check the user's answer.

I found a blog post about this but it didn't seem to support input bindings: https://www.arka.com/blog/dynamically-generate-angular-components-from-external-html

It would be ok for me to have just static attributes but I have to find a way to pass data to the embedded component.

There was also a good solution for this called ng-dynamic but it is no longer maintained and I can't get it working: https://www.npmjs.com/package/ng-dynamic

I followed the instructions on this page: https://www.arka.com/blog/dynamically-generate-angular-components-from-external-html The problem was that I couldn't read the attributes with the @Input property. Instead I used the elementRef to read the inputs:

import {Component, ElementRef, Input, OnInit} from '@angular/core';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
  constructor( private elementRef: ElementRef) {
    let el: HTMLElement = this.elementRef.nativeElement;
    console.log(el.getAttribute("question"));
    this.question = el.getAttribute("question");
    this.answer = el.getAttribute("answer");
  }

  @Input() question;
  @Input() answer;
  isHidden = false;

  ngOnInit() {
  }
}

I still don't know how could we use content projection.

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