Html 使用 Typescript 隐藏元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48100152/
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
Hide elements using Typescript
提问by JanithCW
I'm new to Typescript and Angular Material. I want to hide elements inside elements like this.
我是 Typescript 和 Angular Material 的新手。我想在这样的元素中隐藏元素。
<div id="abc">
<div id="123">
<p>Hello!</p>
</div>
<p>World</p>
</div>
<div id="def">
<p>Hello World</p>
</div>
I want to hide div block(id:123).I tried in this way.
我想隐藏div块(id:123)。我用这种方式尝试过。
var formElement = <HTMLFormElement>document.getElementById('123');
formElement.style.display='block';
It gets an error saying Cannot read property 'style' of null....How can I solve this problem.
它收到一条错误消息,说无法读取 null 的属性“样式”...。我该如何解决这个问题。
回答by Armen Vardanyan
This is not the way to hide elements in Angular. Bind your element's style attribute to a boolean, like this:
这不是在 Angular 中隐藏元素的方法。将元素的样式属性绑定到布尔值,如下所示:
<form [style.display]="isVisible ? 'block' : 'none'">... contents</form>
And in your component class:
在您的组件类中:
this.isVisible = false; // whenever you need to hide an element
Or you can use *ngIf
:
或者你可以使用*ngIf
:
<form *ngIf="isVisible">... contents</form>
Please, note that *ngIf
removes the node and its children completely from the DOM tree completely if the conditions turns to false
, and fully recreates them from scratch when the condition turns true
.
请注意,*ngIf
如果条件变为false
,则从 DOM 树中完全删除节点及其子节点,并在条件变为 时从头开始完全重新创建它们true
。
回答by santosh singh
You can access the dom element using ViewChild
with #localvariable
as shown here,
您可以使用ViewChild
#访问 dom 元素 ,localvariable
如下所示,
import {Component, NgModule,ViewChild,ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div id="abc">
<div #id id="123">
<p>Hide!</p>
</div>
<p>World</p>
</div>
<div id="def">
<p>Hello World</p>
</div>
`,
})
export class App {
name:string;
@ViewChild('id') el:ElementRef;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
ngAfterViewInit()
{
this.el.nativeElement.style.display='none';
console.log(this.el.nativeElement);
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
回答by Parthan_akon
The simplest way to hide elements using DOM is
使用 DOM 隐藏元素的最简单方法是
document.getElementById('123').hidden = true;
in typescript.
在打字稿中。