我试图让HTML标签(选择,按钮或输入)动态分配属性,但我不知道如何在切换中做到这一点,如果你有一个更好的主意,我会很感激,如果你能分享它
我想在标签的开关里面识别一个or或,但是我不明白,我有点迷路了
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appSetValitadions]'
})
export class SetValitadionsDirective {
validations = [
{
typeTagHTML: "select", //(Input, Select)
tagName: "btnSaveDoc",
required: "true",
readonly: "true",
title: "Example title",
Icon: ""
},
{
typeTagHTML: "input",
tagName: "btnSaveDoc",
required: "false",
readonly: "false",
title: "Example title",
Icon: ""
},
{
typeTagHTML: "button",
tagName: "btnSaveDoc",
required: "false",
readonly: "false",
title: "Example title",
Icon: ""
}
]
constructor(el: ElementRef, renderer: Renderer2) {
this.setAttributes(el);
}
setAttributes(el: ElementRef){
let validation;
//PROBLEM
switch (el.nativeElement.tag) {
case "input":
validation= this.validations.find(validation => validation.tagName == el.nativeElement.name);
el.nativeElement.setAttribute("required", validation?.required);
el.nativeElement.setAttribute("readonly", validation?.readonly);
break;
case "select":
validation = this.validations.find(validation => validation.tagName == el.nativeElement.name);
el.nativeElement.setAttribute("required", validation?.required);
el.nativeElement.setAttribute("readonly", validation?.readonly);
break;
case "button":
validation = this.validations.find(validation => validation.tagName == el.nativeElement.name);
el.nativeElement.setAttribute("title", validation?.title);
break;
default:
break;
}
}
}
你访问了错误的交换机属性应该是el.nativeElement.tagName
而不是el.nativeElement.tag
const validations = {
'A': {
attrs: {
required: "true",
readonly: "true",
title: "Example title",
Icon: ""
}
},
'INPUT': {
attrs: {
required: "false",
readonly: "false",
title: "Example title",
Icon: ""
}
}
}
,然后应用属性给给定的HTML元素,像这样:
constructor(el: ElementRef, renderer: Renderer2) {
this.setAttributes(el.nativeElement);
}
setAttributes(el: HTMLElement) {
const attrs = validations[el.tagName].attrs;
Object.keys(attrs).forEach(attrName => {
el.setAttribute(attrName, attrs[attrName]);
});
}