Angular2 ViewChild does not reference child elements within a ngIf

2

I have the following problem in a component, I need to access a child element within the component but this being within a *ngIf when the component is initialized gives me an invalid reference or undefined as I can solve this problem , for when the div is shown the reference to the child component is valid

@Component({
   selector: 'form-component',
   templateUrl: 'form-component.html' 
})
export class FormComponent implements OnInit{
  @ViewChild('input') input: ElementRef;
  public mostrar: boolean;


  ngOnInit() {
    console.log('input', this.input.nativeElement);
  }

  showForm() {
    this.mostrar = true;
    this.input.nativeElement.focus() // Dara error porque no se puedo establecer la referncia al elemento del DOM.
  }

}

form-component.html (here does not work)

<div *ngIf="mostrar">
  <input type="text" #input>
  <input type="text">
  <input type="text">
</div>
<button (click)="showForm">mostrar</button>

If the referenced item is outside the div with the %%% code, there is no problem:

form-component.html (this works)

<input type="text" #input>
<div *ngIf="mostrar">
  <input type="text">
  <input type="text">
</div>
<button (click)="showForm">mostrar</button>

I understand how the content is not drawn when initializing the component, but I do not know how to establish the reference after it was created for when the element I want to reference is drawn.

    
asked by Ricardo D. Quiroga 13.04.2018 в 17:12
source

2 answers

3

It is not possible to reference a child that is inside an * ngIf, a typical workaround is to use hidden.

<div [hidden]="!mostrar">
     <input #miInput>
</div>
    
answered by 17.04.2018 / 15:35
source
1

Try assigning a setTimeout to wait until the angle finishes updating the view and the elements in question:

  showForm(){
    this.mostrar = true;
    setTimeout(()=>{
        this.input.nativeElement.focus();
    });
  }

What happens with your code is that angular does not update the view just at the time of reassigning the variable this.mostrar , but once finished the execution of the method, proceeds to update the references of the objects affected by the change. The setTimeout what it does is wait for this process to finish and then it has to assign the variable input and then get the reference of it.

    
answered by 17.04.2018 в 02:56