首页 > 解决方案 > 从 Angular 9 升级到 10 后自定义 CDK 步进器不起作用

问题描述

最近,我按照这里的角度更新指南从 Angular 9 到 10。我更新了 core、cli、material、cdk、ngrx 等,并进行了“ng update”以确保一切都正确迁移。然后我编译并构建它没有任何错误/警告,一切正常,除了cdk stepper,它没有显示任何 cdk 步骤和内容 <cdk-stepper></cdk-stepper>

图片:Angular 10

但它在 Angular 9 中运行良好

图片:角度 9

这是我自定义的 cdk stepper 组件 .ts 和 html:

import { animate, AnimationEvent, state, style, transition, trigger } from '@angular/animations';
import { CdkStepper, StepContentPositionState } from '@angular/cdk/stepper';
import { AfterContentInit, ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { Subject } from 'rxjs/internal/Subject';
import { distinctUntilChanged, takeUntil } from 'rxjs/operators';

@Component({
    selector: 'cdk-stepper',
    templateUrl: './cdk-stepper.component.html',
    styleUrls: ['./cdk-stepper.component.scss'],
    providers: [{ provide: CdkStepper, useExisting: CdkStepperComponent }],
    animations: [trigger('stepTransition', [
        state('previous', style({
            transform: 'translateY(-100%)', zIndex: -1,
            opacity: 0
        })),
        state('current', style({
            transform: 'translateY(0)', zIndex: 0,
            opacity: 1
        })),
        state('next', style({
            transform: 'translateY(100%)', zIndex: -1,
            opacity: 0
        })),
        transition('* => *', animate('700ms cubic-bezier(0.35,0,0.25,1)'))
    ])],
    changeDetection: ChangeDetectionStrategy.OnPush,
})

export class CdkStepperComponent extends CdkStepper
    implements AfterContentInit {

    currentVerticalLine = {
        'height': '20vh',
        'transition': 'height 200ms ease',
        'top': '-3%'
    }

    @Output() readonly animationDone: EventEmitter<void> = new EventEmitter<void>();
    _animationDone = new Subject<AnimationEvent>();

    @Input() stepHeaderNumber;
    stepHeaderTitle = ['Scan Tenant', 'Mailbox Rules', 'Audit Logs', 'Summary']

    @Input('setSelectedIndex') set setSelectedIndex(index: number) {
        this.updateIndex(index);
    }

    @Output() updateMyIndex: EventEmitter<number> = new EventEmitter();

    updateIndex(index: number) {
        console.log(index)
        this.selectedIndex = index;
        this.updateMyIndex.emit(index);
    }

    onClick(index: number): void {
        this.selectedIndex = index;
    }

    ngAfterContentInit() {
        console.log(this.steps)
        // Mark the component for change detection whenever the content children query change
        this.steps.changes.pipe(takeUntil(this._destroyed)).subscribe(() => {
            this._stateChanged();
        });

        this._animationDone.pipe(
            // distinctUntilChanged to avoid emitting the same event twice,
            // as some browsers callback invokes '.done' twice.
            distinctUntilChanged((x, y) => {
                return x.fromState === y.fromState && x.toState === y.toState;
            }),
            takeUntil(this._destroyed)
        ).subscribe(event => {
            if ((event.toState as StepContentPositionState) === 'current') {
                this.animationDone.emit();
            }
        });
    }

    checkProgress(index) {
        if (this.selectedIndex > index) {
            return true;
        }
        else {
            return false;
        }
    }
}
<div class="container">

    <app-vertical-steps [steps]="steps" [titles]="stepHeaderTitle" [(current)]="selectedIndex" (currentChange)="updateIndex($event)"></app-vertical-steps>

    <div class="cdk-vertical-content-container">
        <div *ngFor="let step of steps; let i=index;" class="cdk-vertical-content ng-trigger ng-trigger-stepTransition"
             [@stepTransition]="_getAnimationDirection(i)" [attr.tabindex]="selectedIndex === i ? 0 : null"
            [id]="_getStepContentId(i)" (@stepTransition.done)="_animationDone.next($event)"
            [attr.aria-labelledby]="_getStepContentId(i)" [attr.aria-expanded]="selectedIndex === i">
            <mat-card class="cdk-card" [class.hidden]="selectedIndex !== i">
                <ng-container [ngTemplateOutlet]="step.content"></ng-container>
            </mat-card>
        </div>
    </div>

</div>

以下是我使用 cdk-stepper 作为子组件的父组件容器:

import { Component, OnDestroy, OnInit } from "@angular/core";
import { select, Store } from '@ngrx/store';
import { combineLatest } from 'rxjs';
import { GraphActions } from 'src/app/actions';
import { fetchSummaries } from 'src/app/entities/event-summary/event-summary.actions';
import * as fromRoot from 'src/app/reducers';


@Component({
    selector: "app-container",
    templateUrl: "./container.component.html",
    styleUrls: ["./container.component.scss"]
})
export class ContainerComponent implements OnInit, OnDestroy {
    pending = false;
    myIndex = 0;
    constructor(
        private store: Store<fromRoot.State>
    ) { }

    ngOnInit() {

        combineLatest(
            this.store.pipe(select(fromRoot.getInitialized)),
            this.store.pipe(select(fromRoot.inboxRulesFetched)),
            this.store.pipe(select(fromRoot.getUsers))
        ).subscribe(([initialized, fetched, users]) => {
            if (initialized) {
                this.store.dispatch(fetchSummaries());
                if (!fetched) {
                    for (let index = 0; index < users.length; index++) {
                        const identity = users[index].id;
                        const mail = users[index].mail;
                        if (mail !== null && users[index].userType !== 'Guest') {
                            this.store.dispatch(GraphActions.fetchGraphInboxRules({ identity }))
                        }
                    }
                }
            }
        })
    }

    ngOnDestroy() {
    }

    setIndex($event) {
        this.myIndex = $event;
    }
    setPendingScan($event) {
        this.pending = $event;
    }
}
<div class="container">
    <app-log-scanning-icon [pendingScan]="pending"></app-log-scanning-icon>
    <cdk-stepper [setSelectedIndex]="myIndex" (updateMyIndex)="setIndex($event)">
        <cdk-step>
            <app-introduction (indexChange)="setIndex($event)" (pendingScan)="setPendingScan($event)"></app-introduction>
        </cdk-step>
        <cdk-step>
            <app-mailboxes (indexChange)="setIndex($event)" [currentStep]="myIndex === 1"></app-mailboxes>
        </cdk-step>
        <cdk-step>
            <app-audit-logs (indexChange)="setIndex($event)" [currentStep]="myIndex === 2"></app-audit-logs>
        </cdk-step>
        <cdk-step>
            <app-summary (indexChange)="setIndex($event)" [currentStep]="myIndex === 3"></app-summary>
        </cdk-step>
    </cdk-stepper>
</div>

如果有人可以提供帮助或提供任何提示,我将不胜感激为什么它不适用于 angular 10 .. 或者我的代码的任何部分都被委派了?谢谢。

PS这里是我的package.json版本列表:package.json

标签: angularangular-materialangular-cdkangular10

解决方案


面临同样的问题。问题是 CdkStepperComponent 组件中的 ngAfterContentInit() 。在版本 10 中,您必须调用 CdkStepper 父类的 super.ngAfterContentInit(),显然从版本 10 开始,这些步骤在此方法中初始化。


推荐阅读