【问题标题】:Component view ngClass not updating组件视图 ngClass 未更新
【发布时间】:2017-05-12 10:45:44
【问题描述】:

我目前正在将 @ngrx 状态管理包合并到一个已经存在的 Angular2 应用程序中。到目前为止,一切都顺利进行,但我遇到了一个问题,即当返回到前一个组件并通过应用商店维护状态时,[ngClass] 指令无法正常工作。

我试图实现的功能是当用户单击一个类别时,该链接使用组件类上的一个名为“selectedCategory”的属性获得一个 css 类“活动”,该属性在 @ngrx 商店中更新。当用户单击单个产品时,会将它们带到单独的产品组件中。然后,当用户返回到原始组件时,应该再次为链接赋予类“活动”,因为“selectedCategory”存储在@ngrx 存储中。虽然这不起作用,而且我的 [ngClass] 指令似乎没有按应有的方式工作。

这是我的代码(请注意,这一切都在我们说话时进行了重构,因此请忽略您可能认为看起来很奇怪的任何内容)。

分类树组件

@Component({
    selector: 'category-tree',
    templateUrl: './app/views/directives/category-tree-view.html'
})

export class CategoryTree {
    @Input() categories: Category[];
    @Output() categoryChange:EventEmitter<any>;
    contentLoaded = false;
    selectedCategory: Category;
    categoriesLower = [];
    APIError = [];

    constructor(
        private _categoryService: CategoryService,
        private _store: Store<ProductViewerStore>
    ) {
        this.categoryChange = new EventEmitter();

        _store.select('selectedCategory')
            .subscribe((selectedCategory) => {
                this.selectedCategory = selectedCategory;
            });
    }

    categoryClick(category) {
        this._store.dispatch({ type: 'MAKE_CATEGORY_SELECTED', payload: category });
        this.getCategoriesLower(category);
    }

它的观点:

<li *ngFor="let category of categories" class='desktop-menu'>
    <span (click)="categoryClick(category)" [ngClass]="{'selected' : category === selectedCategory}">{{category.name}}</span>
    <ul *ngIf="category.sub_categories"  class='sub-category'>
        <category-tree [categories]="category.sub_categories"></category-tree>
    </ul>
</li>

和 selectedCategory @ngrx 减速器:

import {Category} from "../../classes/Category";

export const selectedCategory = (state: Category, action) => {
    switch(action.type) {
        case 'MAKE_CATEGORY_SELECTED':
            return action.payload;
        case 'RESET_SELECTED_CATEGORY':
            return {};
        default:
            return state;
    }
};

正如您在我的组件代码中看到的那样,selectedCategory 组件正在被存储并在订阅中正确返回。当这个 Observable 返回并解析时,我的视图模板 ngClass 似乎没有运行。任何人都可以在这里看到问题吗?

谢谢

【问题讨论】:

  • 非常有趣的问题。你能创建 plunker。

标签: angular state ngrx-store


【解决方案1】:

如果selectedCatagoryObject,也许你的=== 进行了参考检查,没有正确解析? 看起来没问题,但也许 ngrx 在这方面发生了一些事情?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 2020-07-30
    • 2023-03-17
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多