Issue
I am trying to get the HTML tag (Select, Button or Input) to assign the attributes dynamically but I don't know how I can do it in the switch, and if you have a better idea I would appreciate it if you could share it
I want to recognize inside the switch in the label is a or or , but I don't get it I'm a bit lost
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;
}
}
}
Solution
you're accessing wrong property in your switch it should be el.nativeElement.tagName
instead of el.nativeElement.tag
as a sidenote, you can modify your validations array to turn into an object so that key represents HTML tag name and value is attributes you want to attach to it.
const validations = {
'A': {
attrs: {
required: "true",
readonly: "true",
title: "Example title",
Icon: ""
}
},
'INPUT': {
attrs: {
required: "false",
readonly: "false",
title: "Example title",
Icon: ""
}
}
}
and then apply attributes to given HTML element like this:
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]);
});
}
Answered By - Yogi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.