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.