Implementing dynamic input attributes in Angular 5

Is there a way to dynamically add attributes to an input HTML element in Angular?

This is the code from my component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-transclusion',
  templateUrl: './transclusion.component.html',
  styleUrls: ['./transclusion.component.css']
})
export class TransclusionComponent implements OnInit {

  elements: any;

  constructor() { }

  ngOnInit() {
    this.elements = {};
    this.elements.name = 'TEST1';
    this.elements.type = 'text';
    this.elements.value = '12';
    this.elements.placeholder = 'PRUEBA';
    this.elements.maxlength = '10';

    // This is only for test elements keys
    for (const el in this.elements) {
      if (this.elements.hasOwnProperty(el)) {
        console.log(`${el}: ${this.elements[el]}`);
      }
    }
  }
}

And here is my template:

<input  type="text"
        [attr.name]="elements.name"
        [attr.value]="elements.value"
        [attr.placeholder]="elements.placeholder"
        [attr.maxlength]="elements.maxlength"/>

I am looking for a way to iterate over each attribute dynamically and insert it into the input tag like this:

<input type="text"
       [attr.*for="el in elements"]="el"/>

Do you have any suggestions on how I can achieve this?

Sincerely, Antonio

Answer №1

If you're looking to dynamically modify the properties of a specific <input> element, I suggest using the @ViewChild method in Angular. Here's an example implementation:

import { Component, AfterViewInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-custom-input',
  template: `
    <input #customInput />
    `,
  styleUrls: ['./custom-input.component.css']
})
export class CustomInputComponent implements AfterViewInit {

  @ViewChild('customInput') customInput: ElementRef;

  constructor() { }

  ngAfterViewInit() {
    this.customInput.nativeElement.value = 'Custom Input';
    // Modify other attributes as needed
  }
}

Answer №2

I just solved the problem by utilizing this piece of code:

import { Component, Renderer2, ElementRef, OnInit } from '@angular/core';

@Component({
  selector: 'app-transclusion',
  templateUrl: './transclusion.component.html',
  styleUrls: ['./transclusion.component.css']
})
export class TransclusionComponent implements OnInit {

  elements: any;

  constructor(private renderer: Renderer2, private el: ElementRef) { }

  ngOnInit() {
    this.elements = {};
    this.elements.name = 'TEST1';
    this.elements.type = 'text';
    this.elements.value = '12';
    this.elements.placeholder = 'PRUEBA';
    this.elements.maxlength = '10';

    const div = this.renderer.createElement('input');

    for (const el in this.elements) {
      if (this.elements.hasOwnProperty(el)) {
        this.renderer.setAttribute(div, el, this.elements[el]);
      }
    }
    this.renderer.appendChild(this.el.nativeElement, div);
  }

}

A big thank you to @nikolaus and @gab for all the help!

Answer №3

If you are aiming to configure your input field using attributes, it is recommended to utilize directives instead of a component. Additionally, when you need to make adjustments to the native element where your directive is being applied, consider using the renderer service provided by angular.

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

Executing debounceTime outside of Angular's zone inside a material dialog

I encountered an issue while attempting to filter a list of objects within a mat-dialog popup window. My approach was inspired by this helpful post which suggested using debouncing to optimize Angular change detection on keyUp events. Upon implementing th ...

Identify and monitor changes in every element within an array using Typescript/Angular 2

I am working with a person array that I have displayed in a Primeng datatable. Each object in the array has fields for first name, last name, and age, which are represented as columns in the table. Additionally, there is a column to display the status of e ...

Sorting through an array of objects using a filter method

While following a tutorial, I decided to make some changes to the TypeScript for learning purposes. However, I encountered a problem when trying to create a filter function from a React context script. I have successfully implemented a function called get ...

Experimenting with key directive in the newest version of Angular (9)

I'm currently testing a directive, but I am facing an issue where the length of the value in the directive is always undefined. What could be causing this problem? @Directive({ selector: '[evAutoTab]' }) export class EvAutoTabDirective { ...

Guide on utilizing TypeScript declarations imported as `* as`

Currently, I am working with react-icons and attempting to import all icon definitions using the syntax import * as Icons from 'react-icons/fi'. However, I am facing a dilemma on how to create a type that must be one of the types exported from Ic ...

Guide on implementing Password Confirmation in Angular 7 User Registration

I am currently working on a project that involves creating a user registration form using Angular 7 for the frontend and Laravel 5.8 for the backend. While I have successfully implemented user password confirmation in the backend, I am facing some challeng ...

Development of backend applications using Node.js and Express, coupled with frontend interfaces built with Angular

I created a web application, utilizing Node.js with Express and MySQL for the backend, and Angular framework for the frontend. Check here While everything works smoothly in my local environment (using Mamp and port 3000 for testing), I am encountering dif ...

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

Establishing the initial state in React

Can someone help me with setting the default state in React? I'm working on a project that allows files to be dropped onto a div using TypeScript and React. I want to store these files in the state but I'm struggling with initializing the default ...

Converting JSON data to an Excel file in an Angular application

I'm working on exporting my JSON data to an XLSX file. Despite successfully exporting it, the format in the Excel file isn't quite right. Below is the code I am using: downloadFile() { let Obj = { "data": [12,123], "date": ["2018-10- ...

When working with the latest version of Angular CLI, make sure to include a @NgModule annotation in

Just a heads up: I'm diving into Angular for the first time, so bear with me if I make some rookie mistakes. The Lowdown I've got the latest version of Angular CLI up and running The default app loads without a hitch after 'ng serve' ...

Using Selenium in Java, locate a button based on its text content: How?

I'm facing a challenge with grabbing a particular button on the page. The button has the text Search, but there are multiple buttons present. <button _ngcontent-dqg-c23="" class="cp-mat-small-btn mat-flat-button mat-accent" colo ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

Leveraging property information for a dropdown field

In my index.tsx file, I am fetching data that I pass to the component FormOne. This allows me to access the data in FormOne using props.data const [data, setData] = useState([]); ... return ( ... <FormOne data={data} /> ); I am looking to ...

What impact does control flow have on narrowing variable types?

Having reviewed this particular question, my current focus is on understanding how variables can be narrowed down using control flow. An example: type T1 = { a?: { b: string } } const t1: T1 = {} t1.a.b // displays error, possibly undefined t1.a ...

What is the best way to remove all validators from a different component in Angular 7 using reactive forms?

I need to find a way to clear all validation in a form group on a sibling component when a boolean value is selected on another component within the same application. Is there a solution for achieving this? We have implemented a method in our application ...

Software designed for apple silicon ARM64 running Electron framework

Running the Electron desktop application successfully on X64 using electron-builder and dmg. Now, if we need to run the same application on Apple Silicon (ARM64), we followed the steps below: Installed Xcode 12 and upgraded Mac to Big Sur. Executed " ...

Angular2 and the Use of Environment Variables

I am working on an angular 2/4 app with a node server.js to serve it. I need to access an environment variable for switching between backend endpoints (using localhost for dev and another endpoint for prod). Both the frontend and backend apps are destined ...

Troubleshooting: Angular Firebase's signInWithRedirect() and getRedirectResult() functions are experiencing technical difficulties

Within my AuthService, I have implemented a function for signing in with Google which, depending on the user's device, initiates the sign-in process either with a redirect or a pop-up. The pop-up sign-in functionality is operating smoothly, however, ...

Strategies for Resolving Angular Unsupported Engines Alert

I've encountered issues in my Angular project with Unsupported Engines errors such as: npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@angular-devkit/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...