代码示例:
在指令中创建一个 titleCase 属性,将要转换为标题样式的字段名绑定到它上面:
import { Directive, Input, ElementRef, OnInit } from '@angular/core';
import { TitleCasePipe } from '@angular/common';
@Directive({
selector: '[appTitleCase]'
})
export class TitleCaseDirective implements OnInit {
@Input('appTitleCase') fieldName: string;
constructor(private el: ElementRef, private pipe: TitleCasePipe) { }
ngOnInit() {
const value = this.el.nativeElement[this.fieldName];
this.el.nativeElement[this.fieldName] = this.pipe.transform(value);
}
}
在 HTML 中使用该指令:
在此示例中,指令会将 "value" 属性的值转换为标题样式,并将其应用于输入框上。
注意:为了使用内置的 TitleCasePipe,需要在组件或指令的构造函数中注入它。