Angular2:ngClass无法处理页面加载 [英] Angular2: ngClass is not working on page load

查看:86
本文介绍了Angular2:ngClass无法处理页面加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

constructor(private service: MyService) {    
    this.customer = service.getData();     
    console.log(this.customer.address.postalAddress.streetAddress.length);                
  }


<input required [(ngModel)]="customer.address.postalAddress.streetAddress" 
       [ngClass]="{'ng-dirty': customer.address.postalAddress.streetAddress.length > 0}">

内部控制台浏览器日志15这是计算的地址长度数,但未应用css类。

Inside console browser logs 15 which is number of counted address length yet css class is not applied.


仅在有意复位客户对象时再应用Css,并且再次设置
设置数据,页面加载不起作用。

Css is applied only when on purpose reset customer object and again set data, on page load is not working.


推荐答案

您很可能需要解析器或更改检测。或者最好是两者。

You most probably need a resolver or change detection. Or preferably both.

在您将数据加载到之前,页面会被初始化,而在重置客户对象之前不会再次检查。 Resolve允许您在激活路径和组件之前获取数据,从而消除该问题。

What happens is the page gets initialized before your data is loaded in and not checked again until you reset the customer object. Resolve would allow you to grab data before you activate a route and component thus eliminating that problem.

https://angular.io/guide/router#resolve-pre-fetching-component-data - 这是关于如何使用的角度官方指南使用解析器。

https://angular.io/guide/router#resolve-pre-fetching-component-data - here's angular official guide on how to use resolvers.

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html - 我也建议阅读并使用变化检测。帮助识别并消除这样的问题。

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html - I also would suggest reading up and using change detection. Helps identify and eliminate problems like this.

这篇关于Angular2:ngClass无法处理页面加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆