简体   繁体   English

如何在子组件中访问父组件类

[英]How to access parent component class in child component

I am trying to style parent component class in child component using css . 我正在尝试使用css在子组件中设置父组件类的样式。 How to access parent class in the child component in angular 2 如何在Angular 2的子组件中访问父类

I believe if you import the class for the parent component and pass it into the constructor of the child components class you can access the parent from the child. 我相信,如果您导入父组件的类并将其传递给子组件类的构造函数,则可以从子组件访问父类。

Mind you if you're trying to do conditional styling of the parent based on the child you may want to look at EventEmitters and Outputs (see this http://learnangular2.com/outputs ) 请注意,如果您尝试根据孩子对父对象进行条件样式设置,则可能需要查看EventEmitters和Outputs(请参阅此http://learnangular2.com/outputs

You can get closest classof your child element any class and reach to your required parent element/class 您可以获取任何子类中最接近子元素的类,并达到所需的父元素/类

constructor(private el: ElementRef) {        
}

ngAfterViewInit{
     let parentElement=this.el.nativeElement.closest(".yourparentClassName")[0];
     console.log(parentElement);
     if(parentElement.length>0)
     {
         //apply your style here
         parentElement.style.width=200;
     }
}

Note: closest may not work for IE and Firefox, so you have to write logic in function where it return you closest element. 注意: closest可能不适用于IE和Firefox,因此您必须在函数中编写逻辑以使其返回您最接近的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在子 css 选择器中使用父组件的类 - How to use parent component's class in a child css selector 来自父组件的 Class 在子组件中不起作用 - Class from parent component doesn't work in child component 如何将class从Angular 12和Typescript中的父组件添加到子组件布局? - How to add the class to child component layout from parent component in Angular 12 and Typescript? 使用 scss 访问组件的子 class - Access child class of a component using scss 如何通过父级将css应用于角度的子组件 - How to apply css by parent to child component in angular 如何从父组件设置递归嵌套子组件的样式 - How to style recursively nested child component from parent component 如何将 href 参数从父 vue 组件传递给子组件? - How to pass href parameter from parent vue component to child component? 如何在不影响 React Native 中的子组件的情况下设置父组件的样式 - How to style parent component without affecting child component in React Native 当我们有 2 个子组件时,如何将样式从父组件应用到子组件 - How to apply style to child component from parent component when we have 2 child component 如何从父母的样式组件访问孩子的道具? - How to access child's props from parent's styled-component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM