简体   繁体   English

如何通过 document.getElementById inAngular 更改显示

[英]How to change display by document.getElementById inAngular

I have a scenario where I am generating dynamic elements with the data from backend some what like我有一个场景,我正在使用来自后端的数据生成动态元素,比如

<tr *ngFor="let data of datas" (click)="display(data.id)">

<div id="'full'+data.id" [style.display]=" active? 'block': 'none'">

</div>


</tr> 

My Ts File我的 Ts 文件

export class Component{
active=false;
display(id)
{
document.getElementById(`full${id}`).display="block";

}

}

What I want to do is something like above.我想做的是上面的事情。 I tried something like below but that doesn't work it throws error我尝试了类似下面的方法,但这不起作用它会引发错误

Property 'display' does not exist on type 'HTMLInputElement'类型“HTMLInputElement”上不存在属性“显示”

 import { DOCUMENT } from '@angular/common';
   import { Inject }  from '@angular/core';

export class Component{
 active=false;
constructor(@Inject(DOCUMENT) document) {

   }
    display(id)
    {
    document.getElementById(`full${id}`).display="block";

    }

    }

any suggestions,how to do this.Thanks任何建议,如何做到这一点。谢谢

Property 'display' does not exist on type 'HTMLInputElement'类型“HTMLInputElement”上不存在属性“显示”

That's because HTML elements do not have a property display .这是因为 HTML 元素没有属性display What you're looking for is:您正在寻找的是:

document.getElementById(`full${id}`).style.display='block';

Rather than directly manipulating the DOM, the more Angular way of doing this would be to track the visibility state of each row and drive visibility through NgIf与其直接操作 DOM,更多的 Angular 方法是跟踪每行的可见性 state 并通过NgIf驱动可见性

NgIf: A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. NgIf:一个结构指令,有条件地包含一个模板,该模板基于强制为 Boolean 的表达式的值。 When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause.当表达式的计算结果为 true 时,Angular 呈现 then 子句中提供的模板,当 false 或 null 时,Angular 呈现可选 else 子句中提供的模板。 The default template for the else clause is blank. else 子句的默认模板是空白的。

Here is an example with a single boolean driving the toggle of a single div, but you could do something similar with a map on your data.这是一个示例,其中单个 boolean 驱动单个 div 的切换,但您可以对数据执行类似的操作 map。

@Component({
  selector: 'ng-if-simple',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
export class NgIfSimple {
  show: boolean = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM