I have the following problem in a component, I need to access a child element within the component but *ngIf
when the component is initialized it gives me an invalid reference or undefined
how can I solve this problem, when div
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 (doesn't work here)
<div *ngIf="mostrar">
<input type="text" #input>
<input type="text">
<input type="text">
</div>
<button (click)="showForm">mostrar</button>
If the referenced element is outside div
the directive, *ngIf
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 the component is initialized, but I don't know how to set the reference after it is created for when the element I want to reference is drawn.
it is not possible to reference a child that is inside an *ngIf, a typical workaround is to use hidden.
Try assigning a
setTimeout
to wait for angular to finish updating the view and elements in question:What happens with your code is that Angular does not update the view just at the moment of reassigning the variable
this.mostrar
, but once the execution of the method is finished, it proceeds to update the references of the objects affected by the change. What the setTimeout does is wait for that process to finish and then what it takes to assign the variableinput
and then obtain the reference from it.