简体   繁体   中英

How to access the nested element of a ElementRef.nativeElement in angular

I am using NG-ZORRO library and would like to customize it's DatePicker .
For example, I would like to highlight some of the days with different color like screenshot below, and the days that I would like to highlight are dynamic (based on a date list get from database):
在此处输入图像描述

My idea was create a directive, bind the host element with ElementRef and add custom class to the element with Renderer2 . Here is what I have so far:

html

<nz-date-picker nzInline customDatePicker></nz-date-picker>

ts

@Directive({
    selector: `[customDatePicker]`
})
export class CustomDatePickerDirective {

    constructor(@Host() @Self() @Optional() public hostDatePicker: NzDatePickerComponent, renderer: Renderer2, hostElement: ElementRef) {
        console.log(this.hostDatePicker);
        renderer.addClass(hostElement.nativeElement, 'custom-color');
    }
}

The problem is renderer.addClass will only add the custom class at top element ( <nz-date-picker> element), but the element I need to inject the custom class is within this element, I am thinking if there is any way I can look for the child/nested elements? I inspect the <nz-date-picker> element with devtools, the element that I will need to add the custom class is pretty deep inside (within the red box of the screenshot below): 在此处输入图像描述

You can use vanilla JS for this. Here I just change the color of some of the cells:

@Directive({
  selector: `[customDatePicker]`,
})
export class CustomDatePickerDirective {
  constructor(private hostElement: ElementRef) {}

  ngAfterViewInit() {
    const datePicker = this.hostElement.nativeElement as HTMLElement;
    const rows = datePicker.querySelectorAll('tr');

    for (let i = 0; i < Object.keys(rows).length; i++) {
      const cells = rows[i].querySelectorAll('td');

      if (i % 2 === 0) continue;

      for (let j = 0; j < Object.keys(cells).length; j++) {
        if (j % 2 === 0) cells[j].style.backgroundColor = 'lightcyan';
      }
    }
  }
}

stackblitz: https://stackblitz.com/edit/angular-ivy-wap1jw?file=src/app/custom.directive.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM