html - 在订阅中隐藏 html 元素
问题描述
我现在正在使用 Angular,并且我有一个复选框,我想根据订阅 API 调用的结果使其可见或隐藏。
我的问题是复选框中存在“延迟”变得不可见(默认设置为可见)。我认为这是因为我在订阅中设置了可见性布尔值。
本质上,当进行MAT-CHIP选择时,称为订阅。如果 API 返回任何内容,则布尔值保持为真。如果什么都没有返回,那么它是假的。不幸的是,我必须单击远离 mat-chip 部分的复选框才能消失,这不是我想要的即时。
HTML:
<div class="btn-div" style="justify-content: space-between">
<mat-checkbox color="primary" [formControl]="drilldownSelect" *ngIf="children">Show sector
breakdown</mat-checkbox>
<button mat-button (click)="showSectors = !showSectors">
<mat-icon *ngIf="!showSectors">unfold_more</mat-icon>
<mat-icon *ngIf="showSectors">unfold_less</mat-icon>
</button>
</div>
<mat-form-field class="btn-div" *ngIf="showSectors">
<mat-chip-list #chipList>
<mat-chip *ngFor="let sector of chosenSectors" [removable]="true" (removed)="removeSector(sector)">
{{ sector.service_code + ": " + sector.service }}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
<input placeholder="Sectors" #sectorInput [formControl]="sectorCtrl" [matAutocomplete]="auto"
[matChipInputFor]="chipList" [matChipInputAddOnBlur]="true">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let sector of filteredSectors | async" [value]="sector" matTooltip={{sector.commodity}}
[matTooltipPosition]="'after'" [matTooltipShowDelay]="500">
{{ sector.service_code + ": " + sector.service }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
TS:
selected(event: MatAutocompleteSelectedEvent): void {
this.testMethod(event.option.value.service_code);
}
testMethod(serviceCode: string) {
this.hasChildren(serviceCode).subscribe((codes) => {
codes.length == 0 ? this.children = false : this.children = true;
});
}
hasChildren(serviceCode: string): Observable<any> {
this.serviceCodeAppend = serviceCode + "_";
console.log(this.serviceCodeAppend);
return this.httpClient.get<any>(`${this.backendService.url}/table?code=like.${this.serviceCodeAppend}`).pipe(
catchError(error => {
this.backendService.handleError(error);
return of({});
})
).pipe(shareReplay(1));
}
上面应该包含所有相关代码,使复选框在单击时消失但不能“立即”工作
解决方案
从评论中,您似乎遇到了 Angular 的更改检测没有在您需要时触发的问题,您可以手动执行此操作。
注入你的构造函数
constructor(cdRef: ChangeDetectorRef) { }
然后在你的里面subscribe
this.service.apiCall().subscribe(response => {
// Rest of your code
cdRef.detectChanges();
});
推荐阅读
- javascript - 如何在 javascript 中使用 id 或 class 选择动态创建的元素?
- c# - 无法在 Visual Studio 2017 Enterprise MSTest Selenium Unit Tests C# 中找到/添加订购的测试项目到我的项目
- bootstrap-4 - Angular 6:如何在水平标题导航栏下实现进度条
- c# - Asp Button 不工作也不执行后面的功能
- python - 如何使用 PIL 合并来自 800 张图像的像素数据
- postgresql - 我在插入时遇到 hstore 变量的语法错误
- email - 如何使用 email-ext 插件在 Jenkins 中设置地址?
- c# - FileHelpers async 使用 MultiRecordEngine?
- postgresql - PL/PQSQL 存储过程:这两种方法有什么区别?
- resolve - DCOS 在 resolv.conf 中添加 DNS 条目