node.js - 在 Angular 中,使用 Renderer 相对于 ElementRef 有哪些优势?

标签 node.js angular typescript ecmascript-6 single-page-application

我是 Angular 新手,我尝试使用两个选项创建自己的指令:

  • 选项 1:使用 ElementRef 直接访问元素
  • 选项 2:使用渲染器2

选项 1:

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
    selector: '[appBasicHighlight]'
})
export class BasicHighlightDirective implements OnInit {
    constructor(private elementRef: ElementRef) {}

    ngOnInit() {
        this.elementRef.nativeElement.style.backgroundColor = 'green';
    }
}

选项 2:

import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';

@Directive({
  selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective {

  constructor(private elementRef: ElementRef, private renderer: Renderer2) { }

  ngOnInit() {
    this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'blue');
  }
}

本教程的讲师表示,使用渲染器比直接访问更安全,但没有明确解释原因。他的意思是使用 ElementRef 直接访问 DOM,但从代码中可以看到,Renderer 也使用了 ElementRef。有了这个,我很困惑是什么让 Renderer 比 ElementRef 更安全、更有优势。

最佳答案

来自 Angular 文档

"Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of ElementRef in your code. For more detail, see the Security Guide."

"Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported."

或者另一个解释我们何时需要使用渲染器

The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break).

The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly. This is the recommended approach because it then makes it easier to develop apps that can be rendered in environments that don’t have DOM access, like on the server, in a web worker or on native mobile.

因此,当不支持直接访问原生元素时,您应该使用渲染器

关于node.js - 在 Angular 中,使用 Renderer 相对于 ElementRef 有哪些优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143024/

相关文章:

mysql - Node JS等待一系列mysql查询

node.js - 向特定 channel 发送消息,不起作用

node.js - Google App Engine 上的 NestJS 项目显示错误 "Could not write file"&& "EROFS: read-only file system"

Angular 2 与 ngClass 的双向绑定(bind)

css - Angular UIKit npm 安装

Angular - map 不是函数

entity-framework - 如何为 Breeze 实体生成 typescript 接口(interface)/定义

typescript - 在 GraphQL codegen 中生成正确的类型而不是联合

php - app.post 路由中的express.js res.redirect 未重定向到给定的 URL

java - 系统目录到java列表