Home > Software design >  How to change html input value inside a grandchild component from grandparent component
How to change html input value inside a grandchild component from grandparent component

Time:05-01

I have a WidgetsModule where I've created an input component

input.component.ts

import { AfterViewInit, Component, Input, OnInit, Output, ViewChild } from '@angular/core';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit, AfterViewInit {
  @Input() Nombre:string = '';
  @Input() Placeholder:string = '';
  @Input() Value:string = '';

  constructor() { }
  ngOnInit(): void { }
  ngAfterViewInit(): void {  this.bindFocusAnimation(); }
  onInput(evt:Event):void{ this.Value = (<HTMLInputElement>evt.target).value; }
  bindFocusAnimation():void{
    var materialInput:HTMLInputElement = <HTMLInputElement>document.getElementById(this.Nombre);
    if(materialInput.value && materialInput.value.trim().length > 0)
      materialInput.parentElement.lastElementChild.setAttribute("class", "label-material active");

    // move label on focus
    materialInput.addEventListener("focus", function () {
      materialInput.parentElement.lastElementChild.setAttribute("class", "label-material active");
    });
    // remove/keep label on blur
    materialInput.addEventListener("blur", function () {
      var css = "label-material";
      if(materialInput.value !== undefined && materialInput.value.trim().length > 0)
        css  = " active";
      materialInput.parentElement.lastElementChild.setAttribute("class", css);
    });
  }
}

input.component.html

<div >
    <input  id="{{Nombre}}" type="text" name="{{Nombre}}" value="{{Value}}" (input)="onInput($event)" autocomplete="off">
    <label  for="{{Nombre}}">{{Placeholder}}</label>
</div>

outside the component, I can change the Value's value, but this value is not rendered inside html input. Givin an example, I have a clearFields(); function where I make input.Value = '0', making a console.log() of the component, shows me that the value was correctly changed, but when looking at the html the value is still there

this is the page's code where I render the input component

tipo-componente.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Constantes } from 'src/app/constantes';
import { ApiRequest } from 'src/app/interface/api-request.interface';
import { TipoComponente } from 'src/app/interface/tipo-componente.interface';
import { TipoComponenteService } from 'src/app/services/tipo-componente.service';
import { WidgetsModule } from 'src/app/widgets/widgets.module';

@Component({
  selector: 'app-tipo-componente',
  templateUrl: './tipo-componente.component.html',
  styleUrls: ['./tipo-componente.component.css']
})
export class TipoComponenteComponent implements OnInit {
  tiposComponentes:TipoComponente[];
  id:number;
  tipo:string;
  icono:string;
  constructor(private TipoComponenteSvc:TipoComponenteService) { }

  ngOnInit(): void {
  }
  ngAfterViewInit() {
    this.cargarTiposComponentes();
    this.limpiarCampos();
  }
  cargarTiposComponentes():void{
    const req:ApiRequest = {  
      Usuario:Constantes.usuario.Usuario,
      Contrasenia:Constantes.usuario.Contrasenia,
      Key:Constantes.usuario.Key,
      RequestObject:{ Id:0, Descrip:'' }
    };

    // this.TipoComponenteSvc.cargar(req).pipe(
    //   tap(
    //     res => {
    //       if(res.Status){
    //         this.tiposComponentes = <TipoComponente[]>res.Data;
    //       }
    //       else
    //         console.log(res.Mensaje);
    //     }
    //   )
    // ).subscribe();
  }
  limpiarCampos():void{
    this.id = 0;
    this.tipo = '0';
    this.icono = '';
  }
  btnNuevo_Click():void{
    this.limpiarCampos();
    WidgetsModule.showPanel('pnlTipoComponente');
  }
  btnGuardar_Click():void{
    WidgetsModule.hidePanel('pnlTipoComponente');
    this.limpiarCampos();
  }
  btnEditar_Click(element:TipoComponente):void{
    WidgetsModule.showPanel('pnlTipoComponente');
  }
  btnEliminar_Click(element:TipoComponente):void{
    WidgetsModule.hidePanel('pnlTipoComponente');
    this.cargarTiposComponentes();
  }
}

tipo-componente.component.html

  <section>
    <div >
      <div >
        <div >
            <div >
              <div >
                <h3 >Compact Table</h3>
                <div >
                    <a  id="btnNuevo" (click)="btnNuevo_Click()">
                        <svg >
                            <use xlink:href="#add-1"></use>
                        </svg> Nuevo
                    </a>
                </div>
              </div>
              <div >
                <div  id="pnlTipoComponente" style="display:none">
                  <input type="hidden" id="hfId" [value]="id"/>
                  <div >
                    <app-input Nombre="inTipo" [Value]="tipo" Placeholder="Tipo de Componente"></app-input>
                  </div>
                  <div >
                    <app-input Nombre="inIcono" [Value]="icono" Placeholder="Ícono"></app-input>
                  </div>
                  <div >
                    <a  id="btnGuardar" (click)="btnGuardar_Click()">
                        <svg >
                            <use xlink:href="#add-1"></use>
                        </svg> Guardar
                    </a>
                  </div>
                </div>
                <div >
                  <table >
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Descripción</th>
                        <th>Ícono</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr *ngFor="let tipo of this.tiposComponentes; let index = index">
                        <th>{{ tipo.Id }}</th>
                        <td>{{ tipo.Descrip }}</td>
                        <td>{{ tipo.Icono }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
      </div>
    </div>
  </section>

I'v tried using @ViewChild annotations, EventEmitters, and I can't really remember what else (again stuck with this since the last week xD). I look forward for your answers and thanks in advance

CodePudding user response:

From what I have tested, the problem is that Angular does not bind the variable in the "tipo-componente" component to the variable in the "input" component.

I think the best option you have is using eventEmitter. EventEmitter allows your component to send events. For example:

In your input.component.ts file:

@Output() setInput = new EventEmitter<string>();

onInput(evt:Event) : void {
   this.Value = (<HTMLInputElement>evt.target).value; 
   console.log(this.Value)
   this.setInput.emit(this.Value);
}

This will make your input component send a "setInput" event each time you change the input.

In your tipo-componente.component.html:

<app-input Nombre="inTipo" [Value]="tipo" Placeholder="Tipo de Componente" (setInput)="receiveInput($event)"></app-input>

This will make your app listen to the "setInput" event from app-input and call the receiveInput() method.

In your tipo-componente.component.ts:

receivedInput(event : string){
   this.tipo = event;
}

This will make your app change the value of the variable "tipo" in the "tipo-componente" component.

Fell free to ask for clarification if needed!

EDIT

Please note that the EventEmitter class is the one from @angular/core

  • Related