首页 > 解决方案 > 在订阅中隐藏 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));
    }

上面应该包含所有相关代码,使复选框在单击时消失但不能“立即”工作

标签: htmlangulartypescriptangular-material

解决方案


从评论中,您似乎遇到了 Angular 的更改检测没有在您需要时触发的问题,您可以手动执行此操作。

注入你的构造函数

constructor(cdRef: ChangeDetectorRef) { }

然后在你的里面subscribe

  this.service.apiCall().subscribe(response => {
    // Rest of your code
    cdRef.detectChanges();
  });

推荐阅读