【发布时间】:2021-07-24 13:04:19
【问题描述】:
我想根据布尔变量的值显示或隐藏按钮。为此,我正在使用 Output 属性。但是当页面初始化按钮被隐藏但当 EventEmmiter 发出值时按钮再次被隐藏而不是它必须是可见的。
父组件.ts
showEditButton = false;
editButton(event: boolean) {
this.showEditButton = true
}
父组件.html
<app-tools-menu-items-open
*ngSwitchCase="toolType.FILE_OPEN"
[isTextEditor]="isText"
(showEditButton)="editButton($event)"
></app-tools-menu-items-open>
// This component should be visible if showEditButton is true
<ng-container *ngIf="showEditButton">
<app-tools-menu-items-pdf-edit
*ngSwitchCase="toolType.EDIT_PDF"
></app-tools-menu-items-pdf-edit>
</ng-container>
子组件.ts
@Output('showEditButton') showEditButton = new EventEmitter<boolean>();
uploadFile(event: Event): void {
this.loaderService.shouldLoad(true);
const files = (event.target as HTMLInputElement).files;
if (files && files.length > 0) {
const fileType = files[0].name.substring(
files[0].name.lastIndexOf('.') + 1
);
this.redirectTo(fileType, {
type: TOOL_TYPE.FILE_OPEN,
action: 'file',
value: {
name: files[0].name,
blob: files[0] as Blob,
status: 'selected',
} as FileResource,
});
this.loaderService.shouldLoad(false);
// Emiting the value
this.showEditButton.emit(true);
} else {
// TODO: Handle improper selection.
this.loaderService.shouldLoad(false);
}
}
子组件.html
<div>
<button
mat-icon-button
[matMenuTriggerFor]="options"
(menuOpened)="setToolState(true)"
(menuClosed)="setToolState(false)"
class="icon-btn"
[ngClass]="{ active: isActive }"
matTooltip="{{ 'translateOpen' | translate }}"
>
<mat-icon svgIcon="file" class="app-icon-hover"></mat-icon>
</button>
<mat-menu #options="matMenu">
<button mat-menu-item (click)="openMyDocuments()">
<mat-icon svgIcon="local_drive" class="app-icon-hover"></mat-icon>
{{ "translateMyDocuments" | translate }}
</button>
<input
type="file"
#fileInput
(change)="uploadFile($event)"
accept=".pdf, .txt, .text, .epub"
/>
<button mat-menu-item (click)="openOneDrive()" *ngIf="envName !== 'prod'">
<mat-icon svgIcon="one_drive" class="app-icon-hover"></mat-icon>
{{ "translateOneDrive" | translate }}
</button>
<button mat-menu-item (click)="openGoogleDrive()" *ngIf="envName !== 'prod'">
<mat-icon svgIcon="google_drive" class="app-icon-hover"></mat-icon>
{{ "translateGoogleDrive" | translate }}
</button>
</mat-menu>
</div>
<div #fakeHld id="fakeHld"></div>
在这里,我看到调用了 editButton,但 Angular 中的更改检测不起作用。
【问题讨论】:
-
你确定
editButton被调用了吗? -
@Moshezauros 是的,我使用 console.log() 进行了检查
-
显示子组件模板
-
你能创建一个堆栈闪电战吗?
-
this.showEditButton = true在你的父组件中应该是this.showEditButton = event。
标签: angular typescript angular11