What is the method for dynamically altering attributes using a directive?

I am currently working on dynamically assigning attributes to HTML tags (such as Select, Button, or Input) within a switch statement. However, I'm a bit stuck and would appreciate any better ideas or suggestions you may have.

My goal is to identify whether the label inside the switch corresponds to a Select, Button, or Input, but I'm having trouble figuring it out and navigating through the code.

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;
    }
  }

}

Answer №1

Make sure you are using the correct property in your switch statement - it should be el.nativeElement.tagName rather than el.nativeElement.tag

On another note, consider converting your validations array into an object where the key represents the HTML tag name and the value is the attributes you want to assign to it.

const validationRules = {
    'A': { 
        attrs: {
            required: "true", 
            readonly: "true",
            title: "Example title",
            Icon: "" 
        }
    },
    'INPUT': {
        attrs: {
            required: "false", 
            readonly: "false",
            title: "Example title",
            Icon: "" 
        }
    }
}

Then apply these attributes to the corresponding HTML element like so:

constructor(el: ElementRef, renderer: Renderer2) {
    this.setAttributes(el.nativeElement);
}

setAttributes(el: HTMLElement) {
    const attrs = validationRules[el.tagName].attrs;
    Object.keys(attrs).forEach(attrName => {
        el.setAttribute(attrName, attrs[attrName]);
    });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

Navigating through documents in Jhipster (Angular + Springboot)

After successfully developing a controller and service in the backend using Spring, I have managed to implement file upload functionality on the server. To determine the upload location, I utilized System.getProperty("user.dir") to retrieve the current pr ...

Tips for initiating a component within a loop and terminating it after completing all 3 iterations

Looking for a solution to open and close tags in a loop every 3 iterations. The objective is to create a grid using container, row, and column elements. However, I am unsure how to achieve this. Example: render(){ const arrayName = ["john", " ...

Troubleshooting lack of output in Console.log (NodeJs)

I am facing an issue where I can't see any output when trying to console log a JavaScript code using Node.js. const pokemon = require('pokemon'); pokemon.all(); var name = pokemon.random(); console.log(name); I am unable to even display a ...

Ways to retrieve information from forkJoin

Exploring rxjs for the first time and encountering an issue with forkJoin. In my Angular project, I have a service that combines data from two other services and then returns it to a component. However, when I call this service in my Angular component us ...

Problem Encountered with Modifying Active Link Color in Next.js Following Introduction of Multiple Root Layouts

Currently, I am in the process of developing an application with Next.js and incorporating multiple root layouts from the official documentation at https://nextjs.org/docs/app/building-your-application/routing/creating-multiple-root-layouts. This was neces ...

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

Is it possible to get intellisense for Javascript in Visual Studio Code even without using typings?

Is it possible to have intellisense support in Visual Studio Code for a 3rd party library installed via npm, even if there is no typings file available? I have noticed this feature working in IntelliJ/Webstorm, so I believe it might be feasible. However, ...

Angular interceptors in sequence

I'm looking to implement a queue system in Angular. My goal is to store requests in an array and process them sequentially, moving on to the next request once the current one is successful. Below is the code I tried, but unfortunately it didn't ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

Tips on transforming a grouped object into a table organized by column with the help of Lodash

Looking at my array data: [{ id: '1234', year: 2019 , name: 'Test 1- 2019', rate: 1}, { id: '1234', year: 2020, name: 'Test 2 - 2020', rate: 2 }, { id: '1234', year: 2020, name: 'Test 3 - 2020&apos ...

Is it possible to update both package-lock.json and package.lock simultaneously?

Before releasing to NPM, I always make sure to update the minor version. My usual process includes: - Modifying the package.json - Executing npm i to synchronize package-lock.json with the changes. This prepares both files for publishing. Is there a simpl ...

Double execution of the Angular customFilter function

My goal is to use a custom filter in Angular to filter an array. Essentially, I have a binding set up like this: {{ myData.winners | getWinnerString }}, which returns an array of items with a length ranging from 1 to 4. If the array consists of more than ...

Obtain the content of a dynamic text input field from a nested directive

I recently developed a custom directive using AngularJS that contains a child directive. The child directive's main task is to create various dynamic input elements like textboxes, radio buttons, and checkboxes, each with default values sourced from a ...

Can you please explain the distinction between angular.equals and _.isEqual?

Do these two options offer different levels of performance? Which one excels at conducting deep comparisons? I've encountered situations where Angular's equals function fails to detect certain differences. In addition, I've observed that th ...

Tips for eliminating the left and bottom border in a React chart using Chart.js 2

Is there a way to eliminate the left and bottom borders as shown in the image? ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Is it possible for us to customize the angular material chip design to be in a rectangular shape

I recently implemented angular material chips as tags, but I was wondering if it's possible to customize the default circular design to a rectangle using CSS? ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...