Angular 5 Insert dynamic input attributes

后端 未结 3 385
青春惊慌失措
青春惊慌失措 2021-01-24 09:44

I want to insert dynamically attributes to an input html tag, but I don\'t know to to do this:

I\'ve got this code from component side:

import { Componen         


        
3条回答
  •  难免孤独
    2021-01-24 10:28

    I've just solved it using this

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

    Thanks for all @nikolaus and @gab

提交回复
热议问题