Search code examples
htmlcssangularangular2-components

ngOnInit ignores CSS transition


I have div which I would like to have its width increase from 0 - 100 in a 3s interval using CSS transition property. When I change this property in Chrome Developer tools, it grows nicely from 0-100 along the duration of the 3 seconds. However, if I apply the style from the component's ngOnInit(), it's instant. Am I doing something wrong?

EDIT: I did solve the problem by myself, however an answer which also explains why it works would be great.

Component.ts:

@Component({
    selector: 'notFound',
    templateUrl: 'app/notFound.component/notFound.component.html',
    directives: [ROUTER_DIRECTIVES]
})

export class NotFoundComponent {
    ngOnInit() {
        (<HTMLElement>document.querySelector('.determinate')).style.width = "100%";
    }
}

Component.html:

<div class="wrapper">
    <i class="material-icons error">error_outline</i>
    <div class="not-found-text"> No such page 'round here.</div>
    <a [routerLink]="['Menu']" class="waves-effect waves-light btn blue">
        <i class="material-icons">home</i>
        <!--home-->
    </a>
    <div class="progress">
        <div class="determinate"></div>
    </div>
</div>

<style>
    .progress {
        margin-top: 30px;
        background: white;
    }

    .determinate {
        width: 0%;
        background: #2196F3;
        transition: width 3s ease-in-out;
    }        
</style>

Solution

  • I solved it by wrapping the call in a 0ms setTimeout. What a suprise.

    ngOnInit() {
        setTimeout(function () {
            (<HTMLElement>document.querySelector('.determinate')).style.width = "100%";
        }, 0);
    }