Steve Kanter
Steve Kanter

Reputation: 19

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. 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. 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.

Upvotes: 0

Views: 606

Answers (1)

Silvermind
Silvermind

Reputation: 5944

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:

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

StackBlitz

Thanks to @Eliseo I removed the div prefix, because that is not necessary.

Upvotes: 2

Related Questions