Angular 2 - It is possible to bind the app compone

2019-04-29 06:17发布

I try to bootstrap my main angular component in a pre-executed HTML Document. This is my existing DOM :

<html>
<head></head
<body>

<!-- this is my template generated with Symfony -->
<div ...>
 <ul>
   <li><angularComponent></angularComponent></li>
   <li><angularComponent></angularComponent></li>
 </ul>
</div>

</body>
</html>

I want to bind my Main App Component (or Directive) on body, or on the main div, without replacing my pre generated content (with symfony).

It is possible ? Have you other solution ?

Thanks,

标签: bind angular
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-29 06:40

Usually this is done by adding <ng-content></ng-content> to the template of your Angular AppComponents template, but AFAIK this is not supported on the application component, only on child components.

You could try to set encapsulation: ViewEncapsulation.Native on the AppComponent und use <content></content> instead of <ng-content></ng-content>.

I haven't tried this myself yet.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-29 06:51

Ok, so i haven't found any good answers to this question, here's the (hacky) way I did it:

document.getExistingContentByTag = function(tagName){
    var target = document.getElementsByTagName(tagName)[0];

    if(!target || !target.tagName) return '';

    return target.innerHTML;
}

And to render the template:

@Component({
selector: 'my-app',
template: document.getExistingContentByTag('my-app')
})

So it pulls the content of the my-app tag, does its magic and writes it back.

查看更多
登录 后发表回答