垫选择不会从同级组件重置



当我单击放置垫子选择的组件(child-two)中的按钮时,重置工作,但如果我单击兄弟组件(child-one)中的重置按钮,它就不起作用了。我怎么才能做到呢?

父组件

<div class="styling">
<child-one
(reset)="reset($event)">
</child-one>
</div>
<mat-sidenav #sidenav [mode]="'over'" class="sidenav">
<child-two
class="content-style">
</child-two>
</mat-sidenav>

父组件TS

@ViewChild(ChildOne) childOneComponent;
@ViewChild(ChildTwo) childTwoComponent;
reset($event: boolean) {
if ($event) {
this.childTwoComponent.resetMatSelect();
}
}

ChildTwo组件HTML

<mat-form-field *ngIf="list && list.length > 0" appearance="legacy">
<mat-label>Cities</mat-label>
<mat-select [(ngModel)]="selectedCity"
(selectionChange)="emit($event.value)">
<mat-option [value]="null" i18n>City</mat-option>
<mat-option *ngFor="let city of list"
[value]="city">
{{city?.name}}
</mat-option>
</mat-select>
</mat-form-field>
<button mat-stroked-button (click)="resetMatSelect()">reset</button>

ChildTwo Component TS

resetMatSelect() {
this.selectedCity = null; 
}

childdone组件HTML

<button mat-stroked-button  *ngIf="showResetButton()" (click)="resetFilters()">
<mat-icon>restart_alt</mat-icon>
</button>

childdone组件TS

resetFilters() {
this.filters.cities = null;
this.reset.emit(true);
}

问题解决了,它有一个完全不同的原因,但我认为如果我解释一下,这篇文章可以节省一个或另一个时间。解释:

父组件和子组件之间的绑定正常工作。但是在父组件中使用两次(或多次)相同的子组件时要小心。

在父组件中,我有两个位置的childTwo-component

<div class="styling">
<child-one
(reset)="reset($event)">
</child-one>
</div>
<mat-sidenav #sidenav [mode]="'over'" class="sidenav">
<child-two
class="content-style-port">
</child-two>
</mat-sidenav>
.
. (more code)
. 
<child-two
class="content-style">
</child-two>

我在两个地方使用它的原因是,组件必须具有响应性并且具有特定的宽度,并且它应该消失并"移动"到侧栏。因此,每次单击重置按钮时,都会在不可见的组件中执行重置。

问题解决如下:

<child-two *ngIf="!enableSidenavFilter"
class="content-style">
</child-two>

TS

enableSidenavFilter = false;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.enableSidenavFilter = window.innerWidth < 1000;
}

最新更新