使用指令使用渲染器添加属性 [英] Add attribute with renderer using a directive
问题描述
我想实现扩展带有属性的HTML标记,但将其封装在angular 2组件中.
I want to achieve extending an HTML tag with an attribute but encapsulate this with an angular 2 component.
让我们使用Angular 2组件foo来假定原始标记
Let's assume the original markup using my Angular 2 component foo
<div foo="x"></div>
foo属性应将div转换为:
The foo attribute should transform the div like:
<div some-other-fancy-attribute="x"></div>
首先,我尝试实现一个指令,但无法弄清楚如何使用angular/core中的Renderer向宿主元素添加另一个属性.
First I tried implementing a directive but I could not figure out how to add another attribute to the hosting element using Renderer from angular/core.
然后,我使用[foo]这样的属性选择器了解了Angular 2组件.我喜欢使用模板来呈现其他一些花式属性的想法.
Then I read about Angular 2 components using an attribute selector like [foo]. I liked the idea of using a template to render some-other-fancy-attribute.
但是,模板是在标记后呈现的,所以我最终得到了:
However, the template get's rendered AFTER the tag so I end up with:
<div foo="x">some-other-fancy-attribute="x"
没有简单的方法来封装某些属性创建吗? 认为这是一件微不足道的事,但它给我带来的头痛比预期的要多.
Isn't there an easy way to encapsulate some attribute creation? Thought this is a trivial one but it gives me more headache than expected.
推荐答案
如果我理解的正确. 您的想法很好,应该可以!
If I understood you right.. your idea is good, should work!
请参阅以下示例: https://plnkr.co/edit/YctUpK9r9AqIk0D1qvgZ?p=preview
已更新为使用Renderer2
import {Component, Directive, NgModule, ElementRef, Renderer2, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Directive({
selector: '[foo]'
})
export class MyFancyDirective {
constructor (private _elRef: ElementRef, private _renderer: Renderer2) { console.log('!'); }
ngOnInit() {
this._renderer.setAttribute(this._elRef.nativeElement, 'another-fancy-attribute', 'HERE I AM !!');
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2 #header foo (click)="headerClicked()">Hello {{name}}</h2>
</div>
`,
})
export class App {
@ViewChild('header', { static: true }) header: ElementRef;
name:string;
constructor() {
this.name = 'Angular2'
}
headerClicked() {
console.dir(this.header.nativeElement.attributes['another-fancy-attribute'].value);
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, MyFancyDirective ],
bootstrap: [ App ]
})
export class AppModule {}
这篇关于使用指令使用渲染器添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!