gpt4 book ai didi

angular - 使用指令为渲染器添加属性

转载 作者:太空狗 更新时间:2023-10-29 16:57:59 24 4
gpt4 key购买 nike

我想用一个属性扩展一个 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"

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

最佳答案

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

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

关于angular - 使用指令为渲染器添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39664066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com