Mohamed MILADI
Mohamed MILADI

Reputation: 8081

how to use thymeleaf and angular 4 together?

I've been trying to mix angular with thymeleaf together, but I couldn't find a way. Can any one help me to clear out this confusion !

Upvotes: 0

Views: 5030

Answers (1)

user1409784
user1409784

Reputation:

Assuming you know some angular4, thymeleaf and as you have tagged spring-boot, assume a spring boot application configured for thymeleaf.

By convention spring-boot will look for static resources (css, javascript, ..) in src/main/resources/static.

By convention spring-boot set up for thymeleaf will resolve templates from src/main/resources/templates.

There are many options for including angular4 code, what follows is one very simple approach

below is a top level angular project used to build the java script code and a typical spring boot layout showing directories laid out following convention

basic layout

After you have built your java-script bundles you copy them into the src/main/resources/static/js directory. I am not using the production build bundles as its easier to show whats going on but you would follow the same approach with a production build.
js bundles

You would make a thmeleaf view to inject into a thymeleaf layout.

<head>
    <title>Admin Panel</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="js/favicon.ico?v=2">
</head>
<th:block layout:fragment="content">
    <div class="ang-comp">
    <demo-app >Loading...</demo-app>
    </div>
    <script type="text/javascript" src="js/inline.bundle.js"></script>
    <script type="text/javascript" src="js/scripts.bundle.js"</script>
    <script type="text/javascript" src="js/styles.bundle.js"></script>
    <script type="text/javascript" src="js/vendor.bundle.js"></script>
    <script type="text/javascript" src="js/main.bundle.js"></script>
</th:block>

the imports from the .../static/js directory here <demo-app> is the selector for the angular component.

This is the simplest approach, you can use tools, frontend-maven-plugin and gradle-node-plugin
To develop the angular code with the devsever you would need to set up the proxy.conf.json
Code for a simple approach using gradle can be found here simple code
note to resolve the thymeleaf views you can use the SpringBootServletInitializer
note to declare thymeleaf settings in gradle.properties you would do a similar thing with maven properties.

notes
angular production build
thmeleaf fragments
thmeleaf dialects
spring boot conventions

Upvotes: 3

Related Questions