【发布时间】:2020-10-31 00:16:15
【问题描述】:
我有一个指令,我想用它来为输入字段动态添加属性。 哪个有效,它将正确的属性添加到输入字段。但是该属性的指令不起作用。所以我想我需要编译它,在新的Angular中没有编译。
所以我用了Renderer2,但还是不行。
动态添加属性的指令:
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[addAttributes]'
})
export class addAttributesDirective implements OnInit {
@Input() attributes: any;
constructor(private renderer: Renderer2, private el: ElementRef) {}
ngOnInit() {
this.addAttributes();
}
addAttributes() {
const mapping: any = {
FieldUppercase: 'uppercase'
};
this.attributes.forEach((attr: any) => {
const attribute = mapping[attr];
if (attribute) {
this.renderer.setAttribute(this.el.nativeElement, attribute, 'true');
}
});
this.el.nativeElement.removeAttribute('addAttributes');
}
}
所以当我使用时:
<input type="text"
[name]="id"
[id]="id"
class="form-control"
[ngModel]="value"
[attributes]="attributes"
addAttributes />
它将uppercase="true"添加到输入字段,这是正确的。
但是大写的指令不起作用。
指令大写:
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[uppercase]'
})
export class UppercaseDirective implements OnInit {
@Input() attributes: any;
constructor(private el: ElementRef) {
}
ngOnInit() {
console.log('uppercase');
}
}
通常我需要在控制台日志中看到uppercase,但这不起作用。
我做错了什么?
在某些情况下我不能使用管道,所以想这样做。
【问题讨论】:
-
你能检查一下这是否有帮助吗? stackoverflow.com/questions/41298168/…
-
并非如此。我有一个通用指令
addAttributesDirective,我想在其中向输入元素添加新属性。添加了属性,但不执行该指令UppercaseDirective中所述的任何操作。如果我将大写属性单独添加到输入元素,它可以工作。但我想从addAttributesDirective控制它
标签: angular angular-directive angular-pipe