我有一个分页器(来自primeNG),在其中我对onPageChange
事件实施了一些逻辑,如下所示:
<p-paginator
#p
class="paginator_mot"
[alwaysShow]="false"
[rows]="configuredValuePerPage"
[totalRecords]="totalmotrec"
pageLinkSize="3"
(onPageChange)="paginateMotList($event, motDetails)"
>
</p-paginator>
此分页器现在位于compA
中。我希望当我单击CompB
中存在的按钮时,应该触发此onPageChange
事件。这可能吗?请附加一些工作链接,以便更好地理解。
答案 0 :(得分:0)
这是组件通信的共享服务模型的用例,这是一个常见的角度模式。
步骤1使服务具有可观察到的发送事件:
@Injectable({ providedIn: 'root' }) // provide appropriately, this will be a singleton
export class PaginationService {
private pageSource = new Subject(); // keep subjects private
page$ = this.pageSource.asObservable(); // public observable
page(event, motDetails) { // method to trigger subject, change params as needed
this.pageSource.next({event, motDetails});
}
}
第2步将服务注入组件,订阅感兴趣的组件并在触发组件中触发:
@Component({...})
export class ComponentA implements OnDestroy {
private sub: Subscription;
constructor(private paginationService: PaginationService) {
// subscribe to event, store subscription
this.sub = this.paginationService.page$.subscribe(({event, motDetails}) => {
// trigger onPageChange event here, not sure if this is correct from your given code.
this.paginateMotList(event, motDetails);
});
}
ngOnDestroy() {
this.sub.unsubscribe(); // unsubscribe from events to avoid memory leaks
}
}
@Component({...})
export class ComponentB {
constructor(private paginationService: PaginationService) { }
page(event, motDetails) { // call this method to trigger the event with needed params
this.paginationService.page(event, motDetails);
}
}