【问题标题】:How do I detect class of parent element/component如何检测父元素/组件的类
【发布时间】:2019-11-16 02:40:54
【问题描述】:

当某个类存在于某个父组件/元素中时,我希望 Angular 组件的内容发生变化。与 :host-context() CSS 选择器非常相似,但在 TypeScript 组件代码中。

使用:host-context(.the-class),我可以控制组件中元素的可见性,但这只会修改组件的样式。我也想修改行为。

我还尝试了带有$(this.element.nativeElement).parents().hasClass("the-class"); 的JQuery 路由。这工作得相当好,但我更喜欢声明性/角度的方法。

@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.
  */
}

那么...在不使用 JQuery 或原生 DOM 选择器的情况下,最好的“Angular 方式”是什么?我意识到这可能不是一个常见的用例,因为它会破坏组件隔离等等。但我想,既然:host-context 选择器是为了样式而存在的,那么控制器肯定也有类似的东西。

【问题讨论】:

标签: angular typescript


【解决方案1】:

您可以在子组件中阅读您的父样式表,这样您就可以轻松找到该类。

为了经验;

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

这里的样式 URL 角度允许添加多个样式表,所以您可以在这里添加您的父样式,然后您可以使用 js 方法查找类document.getElementsByClassName(names);

【讨论】:

    【解决方案2】:

    您可以在 Angular 中很好地实现这一点。

    首先你可以声明一个变量来获取有问题的类,比如

    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
    

    有了它,你应该可以为所欲为。

    假设你的类是一个输入或任何与之相关的元素,你也可以在你的 Angular 组件中做这样的事情

    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;    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 2016-01-16
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 2019-11-05
      • 1970-01-01
      相关资源
      最近更新 更多