Angular 中可以通过使用 ngTemplateOutlet 指令实现类似于 Vue.js 中 component 的功能,同时也可以使用 ngIf 和 ngSwitch 指令来控制组件的显示和隐藏。而对于 keep-alive 功能,需要在组件内手动管理组件状态和数据的缓存,可以使用 Service 或者 RxJS 等方法实现。
示例代码:
// app.component.html
// app.component.ts import { Component, OnDestroy } from '@angular/core'; import { MyService } from './my.service'; import { Subscription } from 'rxjs';
@Component({
selector: 'app-root',
template: '
constructor(private myService: MyService) {}
ngOnInit() { this.subscription = this.myService.getCachedComponent().subscribe((component: any) => { this.cachedComponent = component; }); }
ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
// my.service.ts import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService {
private cachedComponent = new BehaviorSubject
cacheComponent(component: any) { this.cachedComponent.next(component); }
getCachedComponent(): Observable
// my-component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { MyService } from '../my.service';
@Component({ selector: 'my-component', template: '
ngOnInit() { this.myService.cacheComponent(this); }
ngOnDestroy() { this.myService.cacheComponent(null); } }