简体   繁体   English

如何从 Angular 8+ 中的字符串渲染模板?

[英]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我找到了一篇关于此的博客文章,但它似乎不支持输入绑定: 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还有一个很好的解决方案,叫做 ng-dynamic,但它不再维护,我无法让它工作: 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.我按照此页面上的说明进行操作: https ://www.arka.com/blog/dynamically-generate-angular-components-from-external-html 问题是我无法使用 @Input 属性读取属性。 Instead I used the elementRef to read the inputs:相反,我使用 elementRef 来读取输入:

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.我仍然不知道我们如何使用内容投影。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM