NewTech Lover
NewTech Lover

Reputation: 1263

How to change this body manipulation with section manipulation in Angular?

We are trying to change CSS id's based on time. The point is that currently, it manipulates the body. How can we change it into section manipulation?

Angular part

ngOnInit() {
this.run(1000, 10)
}
run(interval, frames) {
    var int = 1;

    function func() {
        document.body.id = "b"+int;
        int++;
        if(int === frames) { int = 1; }
    }

    var swap = window.setInterval(func, interval);
}

HTML

<section class='full-screen'>
...
...
</section>

there are different css snippets for #b1, #b2, #b3... since above code changes these ids during each time period. I assume something should be changed here:

document.body.id = "b"+int;  

How move that function usage from body into above HTML section?

Upvotes: 0

Views: 202

Answers (3)

benshabatnoam
benshabatnoam

Reputation: 7660

  1. Add a Template reference variable in your template for the section tag:

    <section #section class='full-screen'>
       ...
       ...
    </section>
    
  2. Add a @ViewChild decoratored variable in your component's ts file to get this element:

    @ViewChild('section', { read: ElementRef }) mySection: ElementRef;
    
  3. Now you can use it like this in your component's ts file:

    ngOnInit() {
      this.run(1000, 10)
    }
    
    run(interval, frames) {
      var int = 1;
    
      function func() {
        this.mySection.nativeElement.id = "b"+int;
        int++;
        if(int === frames) { int = 1; }
      }
    
      var swap = window.setInterval(func.bind(this), interval);
    }
    

See this simple DEMO

UPDATE:

Note that you're using function func(), this will cause you a scoping problem with using this as your component object. One way to fix this is by using bind function:

var swap = window.setInterval(func.bind(this), interval);

Updated the demo to show this in action.

Upvotes: 1

Flow
Flow

Reputation: 580

You can do it thanks to angular viewChild feature

in your html:

<div #foo class="myClass"></div>

in your component ts file

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
// ....
export MyComponernt implement AfterViewInit {
    // ....
    @ViewChild('foo') foo: ElementRef;
    // ....
    ngAfterViewInit(): void {
        // this is how you manipulate element id properly thanks to angular viewChild feature
        this.foo.nativeElement.id = 'something';
    }
    // ....
}

Upvotes: 0

Sudhir Roy
Sudhir Roy

Reputation: 266

document.getElementById("div_top1").setAttribute("id", "div_top2");

You can use this to change section id.

Upvotes: 0

Related Questions