我有兩個組件-從服務器獲取資料的父組件和將獲取的條目顯示為串列的子組件-但前提是串列不為 null 或為空。
我的問題是(短):即使*ngIf檢查串列是否有一些值,發射也已完成,并且在子組件中我得到第一個發射null專案:。
第二次發射雖然沒問題...... 。
有人有想法嗎?
父組件還包含搜索欄位,您可以在其中搜索條目。這是代碼:
<lookup-area [debounceTime]="100"
(searchValue)="searchChanged($event)"></lookup-area>
<app-virtual-list *ngIf="(channels$ | async)?.length > 0"
[items]="channels$ | async"
[itemHeightPx]="32"
[maxContainerHeightPx]="190 - ((channels$ | async)?.length ? 29 : 0)"
[trackByFn]="trackByFn">
<ng-template let-item>Some template</ng-template>
</app-virtual-list>
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None
})
export class FilterComponent implements OnInit, OnDestroy {
public search$ = new BehaviorSubject('');
constructor(private service: YoutubeSearchService) {
}
public ngOnInit(): void {
this.channels$ = combineLatest([this.service.getYoutubeChannels(), this.search$]).pipe(
map(([channels, search]) => search ? channels.filter(channel => (channel.name || channel.id).startsWith(search)) : channels),
map(channels => channels?.sort((a, b) => (a.name || a.id).localeCompare((b.name || b.id), undefined, { sensitivity: 'base' })))
);
}
public ngOnDestroy(): void {
this.search$.complete();
}
public searchChanged(search: string): void {
this.search$.next(search);
}
public trackByFn(index: number, item: YoutubeChannel): any {
return item.id;
}
}
子組件包含顯示的邏輯。這是代碼:
@Component({
selector: 'app-virtual-list',
templateUrl: './virtual-list.html',
styleUrls: ['./virtual-list.less'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None
})
export class VirtualList<T> implements OnChanges {
// Mandatory
@Input() public items: T[];
@Input() public itemHeightPx: number;
// Optional
@Input() public maxContainerHeightPx: number | undefined; // If undefined, scroll container's height is 100%
public ngOnChanges(changes: SimpleChanges): void {
const { items, itemHeightPx, maxContainerHeightPx } = changes;
if (this.maxContainerHeightPx && (items || itemHeightPx || maxContainerHeightPx)) {
this.setContainerScrollHeight();
}
}
}
我試過了:
- 把所有東西都包進去
<ng-container *ngIf="(channels$ | async)?.length > 0">,但沒有成功 - 包裹在另一個
div,仍然沒有作業
我不知道還有什么可以嘗試的,因為這似乎*ngIf不起作用,這真的很奇怪。
我希望第一個變化是里面的物品,因為這*ngIf就是說明。
uj5u.com熱心網友回復:
不確定我是否理解您的問題,但我已經在您的代碼中看到了不好的地方,因此請嘗試解決它并查看問題是否仍然存在。
您不需要創建 3 個訂閱,一個就足夠了。
<ng-container *ngIf="channels$ | async as channels">
<app-virtual-list
*ngIf="channels?.length"
[items]="channels"
[itemHeightPx]="32"
[maxContainerHeightPx]="190 - (channels?.length ? 29 : 0)"
[trackByFn]="trackByFn"
>
<ng-template let-item>Some template</ng-template>
</app-virtual-list>
</ng-container>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529710.html
上一篇:是否可以從訂閱回傳值?
