Estoy tratando de obtener la etiqueta HTML (Seleccionar, Botón o Entrada) para asignar los atributos de forma dinámica, pero no sé cómo puedo hacerlo en el interruptor, y si tiene una idea mejor, le agradecería que la compartiera. eso
Quiero reconocer dentro del interruptor en la etiqueta es un o o , pero no lo entiendo estoy un poco perdido
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; } } }está accediendo a una propiedad incorrecta en su interruptor, debería ser el.nativeElement.tagName en lugar de el.nativeElement.tag
como nota al margen, puede modificar su matriz de validaciones para convertirla en un objeto, de modo que la clave represente el nombre de la etiqueta HTML y el valor sean los atributos que desea adjuntar.
const validations = { 'A': { attrs: { required: "true", readonly: "true", title: "Example title", Icon: "" } }, 'INPUT': { attrs: { required: "false", readonly: "false", title: "Example title", Icon: "" } } }y luego aplique atributos al elemento HTML dado como este:
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]); }); }