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.