1

I have a component that includes a modal. The modal is wrapped in a <ng-template> tag.

<ng-template #modalm let-modal>
...
   <button type="button" (click)="onSubmit()" class="btn btn-primary">OK</button>
...
</ng-template>

This allows me to open and close the modal from my component.ts file.

constructor(private modalService: NgbModal,
    private activeModal: NgbActiveModal)
...
public openModal(modalm: TemplateRef<any>){
    this.activeModal = this.modalService.open(modalm);    
    const btn = modalm.elementRef.nativeElement.querySelector('.btn-primary');
  }

I would like to access the button element and set a property on it. I am following the accepted answer in How do I find Element inside TemplateRef, calling querySelector off of modalm.elementRef.nativeElement. This gives me an error:

TypeError: modalm.elementRef.nativeElement.querySelector is not a function

Why am I not able to call querySelector in this case?

I understand that I have to use the type TemplateRef due to the modal being wrapped in ng-template. What is the correct syntax for accessing an element in the modal?

NeartCarp
  • 87
  • 9
  • 1
    You should avoid rely on `.querySelector`. Why don't you try to pass the needed option through `NgbModalRef#componentInstance` instead? – developer033 Jul 23 '21 at 22:49
  • @developer033 I could create a separate component for the modal. Is this required or can I access the html element from the component.ts file of that component? – NeartCarp Jul 24 '21 at 05:55

1 Answers1

0

This video from Max NgWizard pointed me in the right direction. For a TemplateRef instance there isn't a way that I could find that allows ts access to the DOM such that a button property can be set. As the comments indicate, setting element properties in a ts file is also not recommended practice. It is better to put a directive like ngClass in the html markup and look for a flag in the ts file. A class in the component css file can be created for this purpose.

First I create a class ".myClass" with the style properties I need in the component css file. Then I can put a conditional directive on my button to add this class, like

<button type="button" (click)="onSubmit()" class="btn btn-primary" [class.myClass]="loadComplete">OK</button>

The boolean loadComplete controls the application of the css class from within the ts file.

The css class needs the !important statement added to override Bootstrap style definitions in my case.

.myClass {
    outline: none;
    border: none !important;
    -webkit-box-shadow: none !important;
    -moz-box-shadow: none !important;
    box-shadow: none !important;
    color: red !important;
  }
NeartCarp
  • 87
  • 9