简体   繁体   中英

How can I inject template section inside my application?

Im building a web application using Angular which receive sections from server side.

Each section contains the following:

  • Html template.
  • CSS rules.

note: sections are small in general.

Im now investigating the best practice to manage the communication between the client and server sides,

my first thoughts was receive the html and css as string and inject them in the document as follows:

interface section {
   html: 'this is html',
   css: 'css rules'
};

then simply inject them in the document:

function addStyleString(str) {
    var node = document.createElement('style');
    node.innerHTML = str;
    document.body.appendChild(node);
}

addStyleString(section.css);



function addHtmlString(str) {
   var node = document.createElement('div');
   node.innerHTML = str;
   document.body.appendChild(node);
}

addHtmlString(section.html);

The issue I found with this approach is when removing the section from the template how to remove its stuff from the html and css code?

Another suggested approach is to fetch the CSS as file and then bind the document with the fetched file.

any suggestions? or better approaches?

Try Angular Universal: server-side rendering

With it You can generate angular components on server. And use it in frontend.

The best approach would be not to fetch HTML/CSS from the server to display it in your Angular application, but fetch structured data (JSON, ...) and render that natively in Angular. Angular is strong at rendering data using templates, so doing it like this will just make your life harder than necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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