angular - Angular 没有运行变更检测
问题描述
我想根据布尔变量的值显示或隐藏按钮。为此,我正在使用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 中的更改检测不起作用。
解决方案
ngOnChanges生命周期在属性的先前值与当前值不同时运行。
OnChanges(changes: any){
if(changes.currentValue !== changes.previousValue){
// white your logic here
}
阅读更多关于ngDoCheck生命周期的信息
推荐阅读
- c# - 调试后从 xmlfile 更改 dll 上的常量值
- intel - 如何将 Intel SGX Remote Attestation 应用于 encalve 在服务器中运行的模型?
- html - 在扰流板标签内与 Audioplayer 接口
- amazon-web-services - ImportModuleError aws lambda。找不到模块“./json.js”
- c# - 更改 ASP.Net Core 5 中的默认页面
- tensorboard - 张量板未显示超出某个点的步骤
- python - Python:如何使用 xarray 编写大型 netcdf
- angular - 如何在 Angular 中使用 Flatpickr 禁用基于日期的日期并访问组件参数
- node.js - 使用 ObjectId 时无法引用其他猫鼬模式
- vbscript - ASP 崩溃 - AD 查询和 AD 配置文件缺少“首字母”的问题