HTML更新Angular中的DIV内容



我的HTML页面中有一个div,就像我的角度应用程序中的这样

<div id="graph" *ngIf="newRequired == 0"></div>

我想在容器中加载一个图形,我的容器代码如下

Element createContainer() {
var e = new DivElement()
..style.height = '300px'
..style.maxWidth = '70%'
..style.marginBottom = '50px';
document.body.append(e);
return e;
}

这个工作很好。。。我面临的问题,因为这个元素是动态的。。因此图形加载在页面的底部。

相反,我想在DIV id="graph"(已经在HTML页面中(中加载该图。

我觉得要做到这一点,我们必须更改这里的代码document.body.append(e(…有人能帮助我如何将DIV id="graph">

如果您试图在div中添加代码,请将document.body.append(e)替换为document.getElementById('graph').innerHTML = e

或者,由于看起来您正在使用jQuery,您可以尝试$('#graph').append(e)

DOM操作——尤其是注入与Angular试图通过其框架实现的目标完全不一致。在我与Angular合作的过去几年里,我从未有过一次需要做这样的事情:document.body.append(e);

您应该做的是在html中使用属性绑定。

所以。。。

Element createContainer() {
var e = new DivElement()
..style.height = '300px'
..style.maxWidth = '70%'
..style.marginBottom = '50px';
document.body.append(e);
return e;
}

将转换为:

组件内:

export class ExampleComponent implements OnInit {
public height: number;
public maxWidth: number;
public marginBottom: number;
...
}

在html:

<div id="graph" *ngIf="newRequired == 0">
<div [ngStyle]="{'height': height, 'max-width': maxWidth, 'margin-bottom': marginBottom}"></div>
</div>

使用这种方法,如果出于任何原因需要更改高度,您所要做的就是更改组件中的属性,html就会更新。如果使用document.body.append(e)的原始方法,则必须手动更新这些值。

最新更新