Dom插入(Scripts与Styles)

    你不必在模块或组件级别提供 DomInsertionService ,因为它已经在根中提供. 你可以在组件,指令或服务中直接注入并使用它.

    你可以使用 DomInsertionService 提供的 insertContent 方法去创建一个 <script><style> 元素到DOM的指定位置. 还有 projectContent 方法用于渲染组件和模板.

    insertContent 方法的第一个参数需要一个 ContentStrategy. 如果传递 ScriptContentStrategy 实例, DomInsertionService 将创建具有给定内容的 <script> 元素并放置在指定的DOM位置.

    1. import { DomInsertionService, CONTENT_STRATEGY } from '@abp/ng.core';
    2. @Component({
    3. /* class metadata here */
    4. })
    5. class DemoComponent {
    6. ngOnInit() {
    7. const scriptElement = this.domInsertionService.insertContent(
    8. CONTENT_STRATEGY.AppendScriptToBody('alert()')
    9. );
    10. }
    11. }

    请参考查看所有可用的内容策略以及如何构建自己的内容策略.

    如何插入Styles

    insertContent 方法的第一个参数需要一个 ContentStrategy. 如果传递 StyleContentStrategy 实例, DomInsertionService 将创建具有给定内容的 <style> 元素并放置在指定的DOM位置.

    请参考ContentStrategy查看所有可用的内容策略以及如何构建自己的内容策略. .

    重要说明: DomInsertionService 不会两次插入相同的内容. 为了再次添加内容你首先应该使用 removeContent 方法删除旧内容.

    如果你传递 HTMLScriptElementHTMLStyleElement 做为 removeContent 方法的第一个参数, DomInsertionService 将删除给定的元素.

    1. import { DomInsertionService, CONTENT_STRATEGY } from '@abp/ng.core';
    2. @Component({
    3. /* class metadata here */
    4. })
    5. class DemoComponent {
    6. private styleElement: HTMLStyleElement;
    7. constructor(private domInsertionService: DomInsertionService) {}
    8. ngOnInit() {
    9. this.styleElement = this.domInsertionService.insertContent(
    10. CONTENT_STRATEGY.AppendStyleToHead('body {margin: 0;}')
    11. );
    12. }
    13. ngOnDestroy() {
    14. this.domInsertionService.removeContent(this.styleElement);
    15. }
    16. }

    insertContent

    • contentStrategy 是方法的重要参数,已经在上方进行说明.
    • 根据给定的策略返回 HTMLScriptElementHTMLStyleElement.
    1. removeContent(element: HTMLScriptElement | HTMLStyleElement): void
    • element 参数是已插入的 HTMLScriptElementHTMLStyleElement 元素,它们应由 insertContent 方法返回.

    has

    has 返回一个布尔值,用于表示给定的内容是否插入到DOM.

    • content 参数是 HTMLScriptElementHTMLStyleElement 元素的内容.