As I embark on creating my own Calendar with Angular, I am faced with the challenge of utilizing innerHTML while ensuring safety measures are in place. Admittedly, I am new to this and must confess that my code may not be the most elegant. Following tutorials and adding components as I progress, I have come up with a function that generates div elements within my HTML using innerHTML. This function is currently stored in a variable and called within the ngAfterViewInit() lifecycle hook.
divAndClassGenerator(){
this.htmlContent = '';
for(let x = this.firstDayIndex; x > 0; x--){
this.htmlContent += `<div class="prev-date">${this.prevLastDay - x + 1}</div>`
}
for(let i = 1; i <= this.lastDay; i++){
if(i === new Date().getDate() && this.date.getMonth() === new Date().getMonth()){
this.htmlContent += `<div class="today" value="${i}">${i}</div>`;
} else {
this.htmlContent += `<div value="${i}">${i}</div>`;
}
}
for(let j = 1; j <= this.nextDays; j++){
this.htmlContent += `<div class="next-date" value="${j}">${j}</div>`
}
let safeHtml = this.sanitizer.bypassSecurityTrustHtml(this.htmlContent);
let myElement = this.renderer.selectRootElement('.days');
this.renderer.setProperty(myElement, 'innerHTML', safeHtml);
return safeHtml;
}
The content above illustrates how innerHTML is utilized to manipulate my HTML structure. I acknowledge that there might be an unnecessary complexity with the use of two variables in this process.
<div class="days" [innerHTML] = "safeInnerHtml">
Furthermore, here is a snippet of the CSS styling that should apply to the dynamically generated divs.
.days {
width:100%;
display: flex;
flex-wrap: wrap;
padding: 0.2rem;
}
.days div{
font-size: 1.4rem;
margin: 0.3rem;
width: calc(30rem/7);
height: 5rem;
display: flex;
justify-content: center;
align-items: center;
text-shadow: 0 0.3rem 0.5rem rgba(0,0,0,0.5);
transition: background-color 0.2s;
}
.days div:hover:not(.today){
background-color: #262626;
border: 0.2rem solid #777;
cursor: pointer;
}
.prev-date ,
.next-date {
opacity: 0.5;
}
.today{
background-color: #7e1616;
}
Despite successfully rendering the calendar dates, the current implementation fails to apply the desired CSS styling. Instead, it seems to inherit styles from previous CSS declarations linked to the parent container of the .days div. This unexpected behavior has led me to experiment with various adjustments over the past few days, involving tweaks to variables, code blocks, and modifications to the DomSanitizer and Renderer2 functionalities.