如何从Angular属性指令中访问元素HTML? [英] How do you access the element HTML from within an Angular attribute directive?
问题描述
Angular文档提供了一个示例,用于创建可更改元素背景颜色的属性指令:
The Angular docs provide an example for creating an attribute directive that changes the background color of an element:
https://angular.io/docs/ts/latest/guide/attribute-directives.html
<p myHighlight>Highlight me!</p>
import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
我还可以使用el.nativeElement
来获取元素的内容(例如Highlight me!
),对其进行修改并更新该元素吗?
Can I also use el.nativeElement
to get the content of the element (e.g. Highlight me!
), modify this and update the element?
推荐答案
实际上,我对您应该做console.log(el.nativeElement)
的评论应该为您指明了正确的方向,但我并不认为输出会是正确的表示DOM Element
的字符串.
So actually, my comment that you should do a console.log(el.nativeElement)
should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element
.
以它可以帮助您解决问题的方式对其进行检查的方法是,在您的示例中执行console.log(el)
,那么您将可以访问nativeElement
对象,并且将看到一个名为innerHTML
.
What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el)
in your example, then you'll have access to the nativeElement
object and will see a property called innerHTML
.
这将为您的原始问题提供答案:
Which will lead to the answer to your original question:
let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element
更新以获得更好的方法:
由于这是公认的答案,并且网络工作者正变得越来越重要(无论如何,这都是最佳实践),所以我想在这里添加Mark Rajcok的建议.
Update for better approach:
Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.
The best way to manipulate DOM Elements
programmatically is using the Renderer:
constructor(private _elemRef: ElementRef, private _renderer: Renderer) {
this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}
编辑
由于现在不推荐使用Renderer
,请使用 Renderer2 代替setProperty
Edit
Since Renderer
is deprecated now, use Renderer2 instead with setProperty
此问题及其答案解释了console.log
行为.
这意味着 console.dir(el.nativeElement)
将是在这种情况下作为控制台中可检查"对象访问DOM Element
的更直接方法.
Which means that console.dir(el.nativeElement)
would be the more direct way of accessing the DOM Element
as an "inspectable" Object in your console for this situation.
希望这会有所帮助.
这篇关于如何从Angular属性指令中访问元素HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!