简体   繁体   English

用其模板完全替换Angular组件标签

[英]Completely replace Angular component tag with its template

I'm creating some custom logic in an Angular site that server-side renders out into another templating service [long story] to then get rendered to the client. 我正在Angular站点中创建一些自定义逻辑,服务器端将其渲染到另一个模板服务中(长话说),然后呈现给客户端。 In doing so, I want to wrap the logic for the other templating service in some components and then have the component's template effectively replace itself so it just renders out its template. 这样做时,我想将其他模板服务的逻辑包装到某些组件中,然后让该组件的模板有效地替换自身,以便仅呈现其模板。

Given: 鉴于:

import { Component } from '@angular/core';

@Component({
    selector: 'app-test',
    template '{{ post_name }}',
})
export class PostTestComponent { }

and then 接着

...
<app-test></app-test>
...

The output ends up being: 输出最终是:

...
<app-test>{{ post_name }}</app-test>
...

But what I want is: 但是我想要的是:

...
{{ post_name }}
...

Is there a way to achieve this? 有没有办法做到这一点? Because of some boring annoying legacy stuff, I'm still on Angular 6.1.x. 由于一些令人讨厌的令人讨厌的旧版内容,我仍然使用Angular6.1.x。 But if there's a way to achieve this with 7 or 8 etc, please let me know - it's possible that might outweigh the legacy cruft. 但是,如果有办法用7或8等来实现这一目标,请让我知道-可能会超过传统技术。

Best I can come up with is creating a directive-like component like so: 我能想到的最好的办法就是创建类似指令的组件,如下所示:

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

@Component({
  selector: '[app-my]',
  template: '{{myprop}}'
})
export class MyComponent implements OnInit {

  constructor() { }

  @Input() myprop: string;

  ngOnInit() {
  }
}

Usage: 用法:

<div app-my [myprop]="'test'"></div>

Rendered html: 呈现的html:

<div _ngcontent-hfa-c42="" app-my="" ng-reflect-myprop="test">test</div>

StackBlitz StackBlitz

Thanks to @Eliseo I removed the div prefix, because that is not necessary. 感谢@Eliseo,我删除了div前缀,因为这不是必需的。

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

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