Sunday, November 25, 2018

trying to get started with the modals in the Angular CDK

Alright, I have not yet been able to make a modal that sits just anywhere or that allows for data to be handed to it or that allows you to click an X to close the modal, but I will share with you what I have. First of all, I penned this blog posting which speaks to how to get rid of a flickering scrollbar that the CDK's paginated list of records can cause. I have had to alter the CSS which goes in styles.css like so:

.cdk-overlay-connected-position-bounding-box {
   display:none !important;
}
.cdk-overlay-container div[dir=ltr] {
   position: absolute;
   margin-top: -500px;
   margin-left: 20px;
   width: 200px;
   height: 200px;
   border: 1px solid #000000;
   background-color: white;
}

 
 

The second style here is the style for our modal and as you can see it is pretty ghetto right now. Hey, I'm just getting started. The dir inline attribute of an HTML tag attempts to define which way text should read and the CDK will make a div with this set to ltr for left-to-right (as opposed to perhaps rtl for right-to-left) and this div wraps the guts of our modal or, you could say, is our modal really. Alright, we are going to need a component for our modal like so:

import { Component} from '@angular/core';
import { President } from '../models/president.model';
@Component({
   selector: 'modal',
   templateUrl: './modal.component.html',
   styleUrls: ['./modal.component.css']
})
export class ModalComponent {
   constructor(){
   }
}

 
 

The CSS and the HTML can be whatever you want them to be for now. If you just want to say "Hello World" well that is about how far I can get right now too. We are going to need a service for our component like so:

import { Injectable } from '@angular/core';
import { ModalComponent } from '../layout/modal.component';
import { ComponentPortal } from '@angular/cdk/portal';
import { Overlay } from '@angular/cdk/overlay';
import { President } from '../models/president.model';
@Injectable()
export class ModalService {
   constructor(private overlay: Overlay) { }
   public open(president:President) {
      const overlayInstance = this.overlay.create();
      const filePreviewPortal = new ComponentPortal(ModalComponent);
      overlayInstance.attach(filePreviewPortal);
   }
}

 
 

Make the modal open from another component with a method like this:

openModal(president:President): void {
   this.modalContract.open(president);
}

 
 

At your outermost God module you need to loop in the service at providers and the component at declarations. The component must also be listed at a new metadata property called entryComponents here which looks like so:

entryComponents: [
   ModalComponent
]

No comments:

Post a Comment