Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 TypeScript getElementById returning null when element does exist

Does anyone know why document.getElementById("startDateText") will return null from the paragraph element below, yet if I move that id to the element above it return as I would expect it to?

The Typescript code is fired from a button and is not javascript embedded in the HTML.

   <p class="card-text text-secondary">Start Date and Time</p>
   <p *ngIf="!isDates" class="card-text text-secondary" id="startDateText"  >{{ Detail$?.StartDateTime | date:"MM/dd/yyyy 'at' h:mma" }}</p>

TypeScript:

 const myElement: HTMLElement = document.getElementById("startDateText");
 myElement.innerHTML =this.eventDetail$.StartDateTime;
like image 388
DarkW1nter Avatar asked Dec 18 '22 20:12

DarkW1nter


1 Answers

ngIf will not just "hide" the element, it will remove it from the DOM, so you won't be able to access it if isDates==true.

Suggestion:

You could use [class.hidden]="!isDates" instead. Hidden class is the combination of the two style properties : visibility=0 and display:None, so the element will be kept in the dom, but it won't be rendered.

like image 130
madjaoue Avatar answered Dec 28 '22 10:12

madjaoue