简体   繁体   中英

How do I detect class of parent element/component

I want the contents of an Angular component to change when a certain class exists in one of the parent components/elements. Very similar to the :host-context() CSS selector, but in the TypeScript component code.

Using :host-context(.the-class) , I can control the visibility of elements in my component, but this will only modify the style of the component. I also want to modify the behavior.

I have also tried the JQuery route with $(this.element.nativeElement).parents().hasClass("the-class"); . This works reasonably well, but I would prefer a more declarative/Angular approach.

@Component({
  template: `
    <p>{{text}}</p>
  `,
  styles: [`
    :host-context(.the-class) p {
      color: red;
    }
  `]
})
class MyComponent {
  text: string;

  /*
    Change content of 'text' if 'the-class' can be found
    in any of the parents here somewhere.
  */
}

So... What is the best way to do this "the Angular way", without resorting to JQuery or native DOM selectors? I realize that this may not be a common use-case, as it would break component isolation and so on. But I figured since the :host-context selector exists for styling, there must be something similar for the controller.

may you can read your parent style-sheet in child component you it will be easy for you to find out the class.

For Exp;

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss', '../parent.component.scss']
})

here in style URL angular allow to add more than one style sheet so may you can add your parent styles here and then may you can use js method to findout class document.getElementsByClassName(names);

you can achieve that quite well in Angular.

First of all you can declare a variable to get the class in question like

const classname = document.querySelector('the-class') as HTMLElement;
let container = classname.parentNode;
console.log(container)  // You can console log this to see the parent class for yourself

With that you should be able to do whatever you want.

Assuming your class is an input or any element related to it you can also do stuffs like this in your Angular component

const classname = document.querySelector('the-class') as HTMLElement;
classname.onClick = () => {
let container = classname.parentNode;
console.log(container)  // You can console log this to see the parent class
let container = classname.parentNode;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM