Search code examples
angularcomponentsdropdownz-index

angular - custom dropdown with z-index not working


I know there are lots of posts about using z-index but I can't seem to find one that answers my question. I am writing a custom drop down component that needs to overlap the elements below it.

Here is a very simplified example that illustrates the point, which appears below or can be viewed in pluker: https://plnkr.co/plunk/pt85B6TvbRRIjjji

Any suggestions greatly appreciated!

Thanks - Jon

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <h3>Custom dropdown - z-index</h3> 
  <div style="position:relative; width:45%;">
      <input type="text" [(ngModel)]="inputString">
      <button (click)="toggleDropdown()">Toggle dropdown</button>
      <div *ngIf="showDropdown" style="z-index: 9999; width:35%; border:1px solid blue;">
          <div *ngFor="let day of days">
              {{day}}
          </div>
      </div>
      <div >
          <p>How can I make the list cover this text when visible?</p>
      </div>
  </div>  
  `
})
export class AppComponent {
  showDropdown:boolean = false; 
  days:string[] = [
    'Monday', 
    'Tuesday', 
    'Wednesday', 
    'Thursday', 
    'Friday', 
    'Saturday', 
    'Sunday'
  ]; 
  inputString:string = this.days[0];
  title = 'z-index with dropdown';
  toggleDropdown() {
    this.showDropdown = !this.showDropdown;    
  }

}

Solution

  • Use absolute positioning if you want it to cover the text.

    <div *ngIf="showDropdown" style="z-index: 10; width:35%; border:1px solid blue; position: absolute; top: 0; left: 0; background-color: white;">
       <div *ngFor="let day of days">
          {{day}}
       </div>
    </div>
    

    https://plnkr.co/edit/NuStX5Ojo5uEXPsQ