Home > OS >  angular showing/hiding DOM elements based on what class they have
angular showing/hiding DOM elements based on what class they have

Time:10-28

I'm going to simplify my problem a bit, because I really want to avoid adding a lot of code, because this is a gigantic project we are working on if I started adding code snippets, there would be a lot of it.

My project has one feature, where you have a list of different div elements in the left column of the page, and they can be individually dragged to the right column, where you can make your own list out of these elements in the order you choose.

These div elements are all the same child component. My task is to add a dropdown to these div elements, but only to the ones that have been dragged to the right column (you can choose additional preferences, once it's in the right column). It shouldn't be there on the divs in the left column.

The only way to differentiate between them is by the class name. The ones on the left have a and the ones on the right get the .

Now I'm wondering if there's a way where I can write some code to the effect: if the element has the class 'left', hide the dropdown, else show the dropdown?

CodePudding user response:

Yes, this is definitely possible.

  1. Create a Directive that has a @HostBinding() for a specific class and just add the directive to every component.
  2. Inject ChildComponent into the constructor of that Directive. You can also inject ViewContainerRef and then call this.viewContainerRef["_data"].componentView.component This will give you reference to that child element that the directive is put on.
  3. Once the @HostBinding('.left') event handler is triggered this will be the function that gets called when the class you're looking for is added. Here you can then access that ChildComponent and then presumably call a method on that child component to show/hide the mat-select

I haven't actually tested this but thats the approach I would take.

CodePudding user response:

You might also achieve this thru your css. Something like

 div[class*="left"] dropdown-element {
     display: none;
        ~or~
     visibility: hidden;
 }
  • Related