【问题标题】:Add attribute with renderer using a directive使用指令添加带有渲染器的属性
【发布时间】:2017-02-01 12:12:24
【问题描述】:

我想用一个属性来扩展一个 HTML 标签,但是用一个 angular 2 组件封装它。

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

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

foo 属性应该像这样转换 div:

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

首先我尝试实现一个指令,但我不知道如何使用来自 angular/core 的渲染器向宿主元素添加另一个属性。

然后我阅读了有关使用 [foo] 之类的属性选择器的 Angular 2 组件。我喜欢使用模板来呈现一些其他花哨属性的想法。

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

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

难道没有一种简单的方法来封装一些属性创建吗? 以为这是一件微不足道的事情,但它让我比预期的更头痛。

【问题讨论】:

  • 很好的问题。我将文本资源包装在自定义标签中,通过以下解决方案,我可以知道资源键是什么!

标签: angular


【解决方案1】:

如果我没听错的话.. 你的想法不错,应该可行!

查看此插件: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 {}

【讨论】:

  • 就是这样,我错过了setElementAttribute方法。 :) 谢谢。
  • Renderer 已弃用,应使用 Renderer2 并将 setElementAttribute 更改为 setAttribute ..
【解决方案2】:

我们可以使用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");
      }
    }

【讨论】:

  • 使用您的代码作为参考,我这样做了this._renderer.setAttribute(this._elRef.nativeElement, 'fxFlex', '30');,在渲染的 DOM 内容中,我观察到 fxFlex 的 camelCase 变成了小写。 ?还是卡住了
猜你喜欢
  • 2016-01-08
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2015-11-06
相关资源
最近更新 更多