ViewChild not working if I add outer div


#1

I am trying to access the ion-datetime element using ViewChild so I can set the default value to today when my field is null. I have it working in one instance, but when I add an outer div for conditional display, it starts coming back as ‘undefined’.

<ion-content>
    <form #f="ngForm">
        <div *ngIf="adding===false || (adding===true && task.AncestorID!==null)">
        <ion-item>
            <ion-label for="startProj">Projected Start Date</ion-label>
            <ion-datetime name="startProj" id="startProj" #startProj displayFormat="MM/DD/YYYY" [(ngModel)]="task.StartDateProjected"></ion-datetime>
        </ion-item>
        </div>
    </form>
</ion-content>

I’m then using

@ViewChild('startProj') startProj;

in ngOnInit(), I’m doing

this.startProj.setValue(new Date().toISOString());

This all works if I don’t have the child div in the form. If I have the div, as shown above, this.startProj is “undefined”. Is there some trick to using ViewChild in this case?


#2

The problem became obvious after I posted. It can’t find it because the div is using *ngIf. Anyway, it works fine if I remove the *ngIf and do css display:none.


#3

[hidden] is another option.