1

In my application I have a help section that is only visible when this.car.helpOpen property is true, and initially the property is false:

<ion-item *ngIf="car.helpOpen">
          <div class="car-help-content" item-content>
            <img src="{{testURL}}" />
            <p class="explanations" [innerHTML]="car.helpText"> </p>
          </div>
 </ion-item>

I have a method that changes the value of this.car.helpOpen to true and after that adds an event handler to all of the <a> elements(car.helpText contains <a> elements) inside the <p> element:

  toggleHelp(input){
    input.helpOpen=!input.helpOpen;
    $("p.explanations").find("a").click(function(e){
      alert(e.target.innerHTML);
    });
  }

But I think that the attachment of event handlers is happening before the *ngIf actually shows the help section, and that's why the event handlers don't get attached. If I remove *ngIf completely and execute the function toggleHelp(), the handlers get attached.

Is there a way I can work around this?

Maybe there is a way to add the event handlers without using jQuery? (without changing the actual innerHTML of the element)

GeForce RTX 4090
  • 3,091
  • 11
  • 32
  • 58

1 Answers1

1

ngIf is a structural directive, it creates/destroys content inside the DOM. you can hide the elemnt by css like add class will make the display:none

What is the difference between *ngIf and [hidden]

You can add a click event to p elemnt and check the target element if it 's a this will look like add event listener to a element with pure javascript without jquery

template

<p [innerHTML]="html" (click)="toggleHelp({},$event)"></p>

toggleHelp function

 toggleHelp(input , e:MouseEvent) : void{
    input.helpOpen=!input.helpOpen;

    console.log('event element',e);
     if ((e.target as HTMLElement).tagName === 'A') { 
       let target = e.target as HTMLElement;

       // everything here will run if you click on a element

       alert(target.innerHTML)
     }
    }

stackblitz example

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91