我试图简化角度的材料手风琴,通过我自己的版本,这是试图简化它一点。我有一个步进组件
<mat-accordion>
<ng-content>
</ng-content>
</mat-accordion>这非常简单,并且有以下方法:
import {
Component,
AfterViewInit,
QueryList,
ContentChildren,
OnDestroy,
Input
} from "@angular/core";
import { StepComponent } from "./step.component";
import { Subscription } from "rxjs";
@Component({
selector: "app-stepper",
templateUrl: "./stepper.component.html",
styleUrls: ["./stepper.component.scss"]
})
export class StepperComponent implements AfterViewInit, OnDestroy {
@Input() closeOthers: boolean = true;
@ContentChildren(StepComponent) children: QueryList<any>;
step = 0;
private subscriptions: Subscription = new Subscription();
constructor() {}
ngAfterViewInit() {
this.children.forEach((child: StepComponent, i: number) => {
this.subscriptions.add(
child.animate.subscribe(() => {
this.setStep(i);
})
);
});
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
setStep(index: number) {
this.step = index;
console.log(this.step);
}
nextStep() {
this.step++;
console.log(this.step);
}
prevStep() {
this.step--;
console.log(this.step);
}
}请注意children订阅。
然后我创建了一个step组件
<mat-expansion-panel [expanded]="expanded"
(click)="animateMe()">
<mat-expansion-panel-header>
<mat-panel-title>
{{name}}
</mat-panel-title>
</mat-expansion-panel-header>
<div>
<ng-content>
</ng-content>
</div>
</mat-expansion-panel>这就是我想隐藏手风琴步骤的复杂性的地方。目前它是基本的,但请容忍我。然后我的代码看起来如下:
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
@Component({
selector: "app-step",
templateUrl: "./step.component.html",
styleUrls: ["./step.component.scss"]
})
export class StepComponent implements OnInit {
@Input() name: string;
@Input() expanded: boolean;
@Output() animate: EventEmitter<void> = new EventEmitter<void>();
constructor() {}
ngOnInit() {}
animateMe() {
console.log("clicked");
this.animate.emit();
}
}注意Output事件。因此,在我的组件中,我现在有以下内容:
<app-stepper #stepper>
<app-step name="Hall"
*ngIf="hall"
[expanded]="stepper.step === 0">
<!-- emitted for brevity -->
<button mat-raised-button
type="button"
color="primary"
(click)="stepper.nextStep()">Next</button>
</app-step>
<app-step name="Video"
[expanded]="stepper.step === 1">
<!-- emitted for brevity -->
</form>
</app-step>
</app-stepper>当我按下下一步的按钮时,它确实扩展了这个“步骤”。但是,如果我单击任何一个标头,虽然我确实看到了控制台日志(因此事件发射器实际上正在发出),但订阅不会被捕获,因此“步骤”不会被重置。
有人知道为什么我的代码:
this.children.forEach((child: StepComponent, i: number) => {
this.subscriptions.add(
child.animate.subscribe(() => {
this.setStep(i);
})
);
});不是被抓了吗?
发布于 2020-02-13 20:25:38
我创建了一个stackblitz,因为这似乎是一个有趣的问题。
如果我正确地理解了这个问题,我认为它实际上是一个#简单的修复。
我已经将click事件从step组件中的mat-expansion-panel移动到mat-expansion-header。
<mat-expansion-panel [expanded]="expanded">
<mat-expansion-panel-header (click)="animateMe()">
</mat-expansion-panel-header>
</mat-expansion-panel>正如您所说,订阅正在启动,但是单击处理程序覆盖了对nextStep的调用,导致其重置。
我想我误解了这个问题的简单性吗?
https://stackoverflow.com/questions/60215425
复制相似问题