簡體   English   中英

如何檢測父元素/組件的類

[英]How do I detect class of parent element/component

我希望當父組件/元素之一中存在某個類時,更改Angular組件的內容。 :host-context() CSS選擇器非常相似,但是在TypeScript組件代碼中。

使用:host-context(.the-class) ,我可以控制組件中元素的可見性,但這只會修改組件的樣式。 我也想修改行為。

我也嘗試過使用$(this.element.nativeElement).parents().hasClass("the-class");進行JQuery路由$(this.element.nativeElement).parents().hasClass("the-class"); 這可以很好地工作,但是我更喜歡聲明性/角度的方法。

@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選擇器的情況下,實現這種“角度方式”的最佳方法是什么? 我意識到這可能不是一個常見的用例,因為它會破壞組件的隔離等等。 但是我認為,因為:host-context選擇器用於樣式設置,所以控制器必須有類似的東西。

也許您可以在子組件中閱讀父樣式表,那么很容易找到該類。

為了Exp;

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

此處的樣式URL angular允許添加多個樣式表,因此可以在此處添加父樣式,然后可以使用js方法查找類document.getElementsByClassName(names); ;。

您可以在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;    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM