2016-09-23 51 views
4

我想實現使用屬性擴展HTML標籤,但使用角度2組件封裝它。使用指令爲渲染器添加屬性

讓我們用我的角2分量富

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

foo的屬性應該轉變像DIV假設原來的標記:

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

首先,我試圖執行一個指令,但我無法弄清楚如何使用來自angular/core的Renderer將其他屬性添加到主機元素。

然後,我使用屬性選擇器(如[foo])閱讀了Angular 2組件。我喜歡使用模板來渲染某些其他花式屬性的想法。

但是,模板獲取的呈現的標籤之後,所以我結束了:

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

是不是有一個簡單的方法來封裝一些屬性創造? 認爲這是一個微不足道的,但它讓我比預期更頭痛。

+0

優秀的問題的setAttribute方法。我將文本資源封裝在自定義標籤中,並使用下面的解決方案,我可以知道資源密鑰是什麼! – MrBoJangles

回答

9

如果我理解你對的.. 你的想法很好,應該工作!

看到這個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 {} 
+0

就是這樣,我錯過了setElementAttribute方法。 :) 謝謝。 – mbue

3

我們可以使用Renderer2

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"); 
     } 
    } 
+0

使用你的代碼作爲參考,我做了this._renderer.setAttribute(this._elRef.nativeElement,'fxFlex','30');'在渲染的DOM內容中,我觀察到fxFlex的camelCase轉爲小寫。 ?仍然卡住 –