首页 > 解决方案 > 如何在 Angular 2 中添加完整的 HTML、CSS 和 JS

问题描述

因此,我使用 Angular 7 开发 Web 应用程序,但是其中一个组件使用旧项目中的复杂样式,所以我打算将静态旧项目中的静态 HTML、CSS 和 JS 粘贴到其中一个 Angular 组件中,该怎么做它?

即,我想在 Angular 组件中粘贴以下 HTML 结构:

<html>
<head>
   ...
   ...
   <link rel="stylesheets"..
   <link rel="stylesheets"..
   <link rel="stylesheets"..
</head>
<body>
   ...
   ...
   ...
   <script src="...
</body>
</html>

请注意,我需要在该静态页面上使用 CSS 和脚本,并且只包含在单个 Angular 组件中,我知道声明我们的项目需要的全局 CSS 和 JS angular.json,但是在这种情况下,我不需要全局 CSS 或全局JS,只包含在那个组件上,那么,怎么做呢?

标签: javascripthtmlcssangular

解决方案


如果您只想在单个 Angular 组件中包含某些样式,那么您可以在模板上使用内联样式进行定义。

style1)用标签包装样式:

@Component({
  template: `
    <style>
    h1 {
      color: blue;
    }
    </style>
    <h1>This is a title.</h1>
    `
})

2)模板标签中的普通内联样式:

@Component({
  template: '<h1 style="color:blue">This is a title.</h1>'
})

您还可以在模板中包含脚本标签,以便在使用此组件时导入 JS 文件。

3) 或者,您可以通过在组件的 CSS 文件中使用来导入 CSS 文件@import

@Component({
  template: '<h1>This is a title.</h1>',
  style: '@import url("custom.css");'
})

推荐阅读