Reputation: 1263
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
Reputation: 7660
Add a Template reference variable in your template for the section
tag:
<section #section class='full-screen'>
...
...
</section>
Add a @ViewChild
decoratored variable in your component's ts file to get this element:
@ViewChild('section', { read: ElementRef }) mySection: ElementRef;
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
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
Reputation: 266
document.getElementById("div_top1").setAttribute("id", "div_top2");
You can use this to change section id.
Upvotes: 0