angularangular-cdkangular-cdk-drag-drop

Angular CDK Drag and Drop added dynamically as a string not working


getAppointmentTemplate() {
    const checker = true;
    return `<div class='appointment' cdkDrag style='padding: 0.5rem;margin: 0.2rem;background-color: #000;border-radius: 5px;color: #fff;'>✅booked</div>`;
}

I am calling this function to append to a div inside my html. But the atribute cdkDrag is not working or not getting applied.

Screenshot of calendar component

So I want to create a system where user inputs a date and an appointment gets booked. This Part is done and working fine. Secondly I want to make it dragable so that the user can drag it to the next date or so. Everything is done the only problem is this. I am unable to apply cdkDrag

days += `<div cdkDropList (cdkDropListDropped)="drop($event)" class="dateEl ${checkToday}">${i} ${this.getDateFromUser[j] === `${i}/${this.month + 1}/${this.year}` ? this.getAppointmentTemplate() : ''}</div>`;

in the same manner cdkDropList is not working either any suggestion would be appreciated. Thanks in advance.


Solution

  • TL;DR Directives won't work when you add them with vanilla javascript.

    Angular is a generative ecosystem. Rather than interacting directly with the DOM, you will spend most of your time interacting with the Angular component tree or generating data to be consumed by templates. Hence this rule of thumb: in an Angular project, any HTML you write should be in an .html file or a component decorator - not in your typescript. There are exceptions, of course, but none of them apply here.

    So, rather than build a string of HTML, we'll change days to an array of objects containing the same data. We'll also create an identical days property at the class level.

    export class CalendarViewComponent {
      /* ... */
      days: Array<{ clazz: string; content: string; appointment?: boolean }> = [];
      /* ... */
      displayCalendar() {
        /* ... */
        let days: Array<{ clazz: string; content: string; appointment?: boolean }> = [];
        let iterator: any = [];
    
        for (let i = this.firtDayOfMonth; i > 0; i--) {
          for (let j = 0; j < this.getDateFromUser.length; j++) {
            if (this.getDateFromUser[j] === `${this.lastDateofLastMonth - i + 1}/${this.month - 1}/${this.year}`) {
              days.push({ clazz: `dummy ${this.lastDateofLastMonth - i + 1}/${this.month - 1}/${this.year}`, content: `${this.lastDateofLastMonth - i + 1}  `, appointment: this.getDateFromUser[j] === `${this.lastDateofLastMonth - i + 1}/${this.month - 1}/${this.year}` });
        /* ... */
        // display all days inside the HTML file
        this.days = days;
      };
      /* ... */
    }
    

    In the template, we'll use Angular control flow syntax to repeat the "dateEl" element for each entry in the days array. We'll make use of text interpolation and an if block as well. When we assign the class-level property, Angular will automatically update the DOM accordingly.

    <div cdkDropListGroup class="dates" #dates id="dates">
      @for (day of days; track day) {
        <div cdkDropList (cdkDropListDropped)="drop($event)" class="dateEl {{ day.clazz }}">
          {{ day.content }}
          @if (day.appointment) {
            <div class="appointment" cdkDrag style="padding: 0.5rem;margin: 0.2rem;background-color: #000;border-radius: 5px;color: #fff;">✅booked</div>
          }
        </div>
      } @empty {
        <div>1</div>
        <div>2</div>
        <div>3</div>
        ...
      }
    </div>
    

    Obviously there's more to be done than what I've shown here, but it should be enough to get you started.