Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Angular doesn't find element by id

I'm learning Angular and I'm building a simple calendar component. I want to give an id to the "td" elements and give them classes based on the backend data. If they are reserved by the customer I will give a class "reserved" and then make the background red. My code looks like this:

<tr *ngFor="let week of createArrays()">
    <td *ngFor="let day of week" id="{{ 'id_' + day }}">{{ day }}</td>
</tr>

This will look like:

<td _ngcontent-ehf-c16="" id="id_21">21</td>

Then in the component.ts I use the service to get the reserved dates and save them in a Set.

  closeDates(): any {
    for (const date of this.reserved) {
      if (date.getMonth() === this.date.getMonth() && date.getFullYear() === this.date.getFullYear()) {
        document.querySelector(`#id_${date.getDate()}`).classList.add('reserved');
      }
    }
  }

After the function runs it still doesn't have the reserved class. If I run the same querySelector code in the console it finds the element and makes the background red.

question from:https://stackoverflow.com/questions/65917860/angular-doesnt-find-element-by-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...