【问题标题】:ngOnInit ignores CSS transitionngOnInit 忽略 CSS 过渡
【发布时间】:2016-10-02 15:22:39
【问题描述】:

我有一个 div,我希望使用 CSS 过渡属性在 3 秒内将其宽度从 0 增加到 100。当我在 Chrome 开发人员工具中更改此属性时,它会在 3 秒的持续时间内从 0 到 100 很好地增长。但是,如果我应用组件的ngOnInit() 中的样式,它是即时的。我做错了吗?

编辑:我确实自己解决了这个问题,但是一个回答也解释了它为什么会很好。

组件.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%";
    }
}

组件.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>

【问题讨论】:

  • 我认为你应该看看 Angular 2 Docs about Lifecycle Hooks。 OnInit 在 OnChanges 之后立即触发一次。您可能需要实现另一个钩子。此外,您可能需要使用导出类为 TypeScript 工具正确实现它,无论实现 hook {} - 通过 hook1、hook2 链接它们

标签: html css angular angular2-components


【解决方案1】:

我通过将调用包装在 0ms setTimeout 中解决了这个问题。真是惊喜。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多