Angular 5 Insert dynamic input attributes

后端 未结 3 350
青春惊慌失措
青春惊慌失措 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

    0 讨论(0)
  • 2021-01-24 10:31

    If you want to dynamically change the attributes of a single <input> tag, I would recommend you use @ViewChild. For example,

    import { Component, AfterViewInit, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-transclusion',
      template: `
        <input #foobar/>
        `,
      styleUrls: ['./transclusion.component.css']
    })
    export class TransclusionComponent implements AfterViewInit {
    
      @ViewChild('foobar') foobar: ElementRef;
    
      constructor() { }
    
      ngAfterViewInit() {
        this.foobar.nativeElement.value = 'foobar';
        // change other values of element
      }
    }
    
    0 讨论(0)
  • 2021-01-24 10:42

    You are following the wrong approach if you want to use attributes to "config" your input field you should use directives instad of a component...
    and if you need to modify the native element on which you are appling your directive use the renderer service shipped with angular

    0 讨论(0)
提交回复
热议问题