angular – 使用指令使用渲染器添加属性
发布时间:2020-12-17 07:33:52 所属栏目:安全 来源:网络整理
导读:我想实现扩展带有属性的 HTML标记,但是用角度2组件封装它. 让我们假设使用我的Angular 2组件foo的原始标记 div foo="x"/div foo属性应该将div转换为: div some-other-fancy-attribute="x"/div 首先,我尝试实现一个指令,但我无法弄清楚如何使用角度/核心的渲
我想实现扩展带有属性的
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" 是否有一种简单的方法来封装一些属性创建?
如果我理解你的话……
你的想法很好,应该工作! 看到这个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 {} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |