typescript Angular 5 移除特定的 DOM 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51019342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 5 remove specific DOM elements
提问by Vlad N
I have a small issue that I can't figure out how to do. I am just learning Angular / Typescript and I can't figure out how I could remove some DOM elements. I have some auto generated content, that has specific CSS classes. Unfortunately The objects are generated somewhere else and I cannot configure them in any way so I cannot add any ngIf or anything else on that content, that would simplify my work... I just have to use them. What I want to achieve is something like this( jQuery version):
我有一个小问题,我不知道该怎么做。我只是在学习 Angular/Typescript,我不知道如何删除一些 DOM 元素。我有一些自动生成的内容,具有特定的 CSS 类。不幸的是,这些对象是在其他地方生成的,我无法以任何方式配置它们,因此我无法在该内容上添加任何 ngIf 或其他任何内容,这将简化我的工作......我只需要使用它们。我想要实现的是这样的(jQuery 版本):
$("#button").click(function() {
$('.fc-oss').toggle();
});
I have a toggle and I want to attach an event to it that when it's being activated, it hides/ shows all elements with that specific type from the view. I am trying to achieve this in angular without jQuery but with little success. Any ideas on how I might be able to achieve this ?
我有一个开关,我想给它附加一个事件,当它被激活时,它会从视图中隐藏/显示具有该特定类型的所有元素。我试图在没有 jQuery 的情况下以 angular 实现这一点,但收效甚微。关于我如何能够实现这一目标的任何想法?
采纳答案by VadimB
In Angular you can use direct access to DOCUMENT.
在 Angular 中,您可以直接访问 DOCUMENT。
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class MyService {
constructor(@Inject(DOCUMENT) private document: any) {}
}
Having this you can access your element and define some logic to it
有了这个,您可以访问您的元素并为其定义一些逻辑
let element = this.document.getElementbyClassName('fc-oss');
element.style.display = element.style.display === 'none' ? 'block' : 'none';
回答by Romain capelleman
You can work with *ngIf="boleanVar"
, init it in your ts 'boleanVar = true'
in your ts and add <br>< button (click)="boleanVar = !boleanVar"> Toggle visibility</button>
您可以使用*ngIf="boleanVar"
,在 ts'boleanVar = true'
中的 ts 中初始化它并添加<br>< button (click)="boleanVar = !boleanVar"> Toggle visibility</button>
回答by Liju Kuriakose
You can use the ngif directive for that.
您可以为此使用 ngif 指令。
@Component({
selector: 'ng-if-simple',
template: `
<button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
show = {{show}}
<br>
<div *ngIf="show">Text to show</div>
`
})
class NgIfSimple {
show: boolean = true;
}
According to the value of the variable show
the div element will toggle view.
根据变量的值,show
div 元素将切换视图。