要在Angular中添加任意属性绑定与指令,可以按照以下步骤进行操作:
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appArbitraryBinding]'
})
export class ArbitraryBindingDirective implements OnInit {
@Input('appArbitraryBinding') appArbitraryBinding: any;
constructor(private el: ElementRef) {}
ngOnInit() {
for (let prop in this.appArbitraryBinding) {
this.el.nativeElement.setAttribute(prop, this.appArbitraryBinding[prop]);
}
}
}
在这个自定义指令中,我们使用了ElementRef
来获取DOM元素,并通过@Input
装饰器来接收传入的任意属性对象。
This is a div with arbitrary attributes.
在这个例子中,我们将一个对象传递给appArbitraryBinding
,其中包含了要绑定的任意属性和值。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ArbitraryBindingDirective } from './arbitrary-binding.directive';
@NgModule({
imports: [BrowserModule],
declarations: [ArbitraryBindingDirective],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,就完成了在Angular中添加任意属性绑定与指令的操作。在运行应用时,指令会将传入的任意属性绑定到相应的DOM元素上。