简体   繁体   中英

HTML Update the DIV content in Angular

I have a DIV inside my HTML page like this in my angular application,

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

I want to load a graph inside the container, my Container code is like this

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

This working fine... the problem I am facing since the element is dynamic one.. so the graph loads at the bottom of the page.

Instead I want to load the graph inside the DIV id="graph" (already inside the HTML page).

I feel to do this we have to change the code here document.body.append(e)... can anyone help me how to bring the graph since the DIV id="graph"

If you're trying to add code inside your div, replace document.body.append(e) with document.getElementById('graph').innerHTML = e .

Alternatively since it looks like you're using jQuery you can try $('#graph').append(e) .

DOM manipulation - especially injection is completely incoherent with what Angular is trying to achieve with its framework. In the last couple years I've spent working with Angular, I've not had a single occasion where I have needed to do something like: document.body.append(e); .

What you should be doing instead is using property binding in html.

So...

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

Will transform into:

In component:

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

In html:

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

With this approach if you need to change your height for whatever reason, all you have to do is change the properties in the component and the html will update. If you go with your original approach of document.body.append(e) you would have to manually update these values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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