'Angular2+ render a component without any wrapping tag at all
My child-component looks like:
...
@Component({
selector: '[child-component]'
templateUrl: './child.template.html'
})
...
and my parent template like:
<span child-component [someInput]="123"></span>
now I want to render the content of my child component without the <span>
container around it. I want no container at all in my parent component's template, just the content of our child-component's template.
I tried some other tags already.
<ng-content>
(nothing rendered at all)<ng-template>
(Components on an embedded template:)<ng-container>
(Failed to execute 'appendChild' on 'Node')
Thanks in advance!
Solution 1:[1]
Finally found a working soltion!
My child-component looks like:
@Component({
selector: 'child-component'
templateUrl: './child.template.html'
})
export class ChildComponent {
@ViewChild('childComponentTemplate') childComponentTemplate: TemplateRef<any>;
}
My child template looks like:
<ng-template #childComponentTemplate>
... some content ...
</ng-template>
and my parent template like:
<child-component #wrapper [someInput]="123"></child-component>
<ng-container *ngTemplateOutlet='wrapper.childComponentTemplate'></ng-container>
This way there is no wrapper at all.
Solution 2:[2]
Your use-case can be solved by using CSS only, just set child-component
as display: contents
,
child-component {
display: contents;
}
As stated on display: contents
documentation, this causes to appear as if the component were direct children of the element's parent.
Solution 3:[3]
This method can avoid ExpressionChangedAfterItHasBeenCheckedError error.
child-component:
@Component({
selector: 'child-component'
templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
@ViewChild('childTemplate', {static: true}) childTemplate: TemplateRef<any>;
constructor(
private view: ViewContainerRef
) {}
ngOnInit(): void {
this.view.createEmbeddedView(this.currentUserTemplate);
}
}
parent-component:
<child-component></child-component>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | CoTg |