使用指令使用渲染器添加属性

时间:2016-09-23 15:08:37

标签: angular

我想实现扩展带有属性的HTML标记,但是用角度2组件封装它。

让我们假设使用我的Angular 2组件foo的原始标记

<div foo="x"></div>

foo属性应该将div转换为:

<div some-other-fancy-attribute="x"></div>

首先我尝试实现一个指令,但我无法弄清楚如何使用角度/核心的渲染器向托管元素添加另一个属性。

然后我使用像[foo]这样的属性选择器来阅读Angular 2组件。我喜欢使用模板来渲染其他花式属性的想法。

但是,模板会在标签之后呈现,所以我最终得到:

<div foo="x">some-other-fancy-attribute="x"

是否有一种简单的方法来封装某些属性创建? 认为这是一个微不足道的,但它让我比预期更令人头疼。

2 个答案:

答案 0 :(得分:18)

如果我理解你的话...... 你的想法很好,应该工作!

请参阅此plunker:https://plnkr.co/edit/YctUpK9r9AqIk0D1qvgZ?p=preview

import {Component, Directive, NgModule, ElementRef, Renderer, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Directive({
  selector: '[foo]'
})
export class MyFancyDirective {

  constructor (private _elRef: ElementRef, private _renderer: Renderer) { console.log('!'); }

  ngOnInit() {
    this._renderer.setElementAttribute(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') 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 {}

答案 1 :(得分:10)

我们可以使用 Renderer2 类的 setAttribute 方法

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

@Directive({
  selector: '[DirectiveName]'
})
export class DirectiveNameDirective implements OnInit {
 constructor(public renderer : Renderer2,public hostElement: ElementRef){}
ngOnInit() {
      this.renderer.setAttribute(this.hostElement.nativeElement, "data-name", "testname");
      }
    }
相关问题