[英]Add a class to a specific dom outside of Component in Angular2
我有一個組件可以根據名為“isVisible”的變量是 True 還是 False 來打開模態。 一旦模態可見,我想向頁面的“body”標簽添加一個類,一旦它關閉,我想從“body”標簽中刪除該類。
下面是我的代碼片段和我嘗試過的內容。
import {Component, ElementRef} from '@angular/core';
@Component({
selector: 'modal',
template: '<div class="modal_div">
<div (click)="closeCard()"></div>
<div class="modal_body">blah</div>
</div>'
})
export class DailogComponent{
isVisible: boolean;
constructor(public element: ElementRef){
this.isVisible = false;
}
OpenModal(){
this.isVisible = true;
//add css class to body here which is where I am lost
console.log(this.element.nativeElement.parentNode.querySelector('body'));
}
closeModal(){
this.isVisible = false;
//remove css class to body here which is where I am lost
console.log(this.element.nativeElement.parentNode.querySelector('body'));
}
}
如果這是錯誤的或 ng 中的反模式,有人會糾正我。
您可以為此使用javascript。 如果我理解正確,您想更改 body 標簽的類。 所以頁面的正文。 <body></body>
和getElementsByTagName()或者是查詢選擇器,就像你所做的那樣,我個人使用 getElementsByTagName 除了我已經習慣之外沒有其他充分的理由。
//don't capitalize function names.
toggleBodyClass(){
this.toggleClass(document.getElementsByTagName('body')[0], 'myclass');
}
//this function is taken from the Stackoverflow thread posted above.
toggleClass(ele, class1) {
let classes = ele.className;
let regex = new RegExp('\\b' + class1 + '\\b');
let hasOne = classes.match(regex);
class1 = class1.replace(/\s+/g, '');
if (hasOne)
ele.className = classes.replace(regex, '');
else
ele.className = classes + class1;
}
測試,工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.