feat(angular,angular-server): angular v14 minimum support (#26822)

BREAKING CHANGE:

Angular v14 is now required to use `@ionic/angular` and `@ionic/angular-server`. Upgrade your project to Angular v14 by following the [Angular v14 update guide](https://update.angular.io/?l=3&v=13.0-14.0).

The dev-preview `environmentInjector` property has been removed from `ion-tabs` and `ion-router-outlet`. Standalone component routing is now available without additional custom configuration. Remove the `environmentInjector` property from your `ion-tabs` and `ion-router-outlet` components.
This commit is contained in:
Sean Perkins
2023-02-22 12:33:49 -05:00
committed by GitHub
parent 3086c5859e
commit 1dee16f3a2
50 changed files with 9867 additions and 72822 deletions

View File

@ -1,34 +0,0 @@
/**
* This class is taken directly from Angular's codebase. It can be removed once
* we remove support for < Angular 14. The replacement class will come from @angular/core.
*
* TODO: FW-1641: Remove this class once Angular 13 support is dropped.
*
*/
import { Injector, ProviderToken, InjectFlags } from '@angular/core';
/**
* An `Injector` that's part of the environment injector hierarchy, which exists outside of the
* component tree.
*
* @developerPreview
*/
export abstract class EnvironmentInjector implements Injector {
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/**
* @deprecated from v4.0.0 use ProviderToken<T>
* @suppress {duplicate}
*/
abstract get(token: any, notFoundValue?: any): any;
abstract destroy(): void;
/**
* @internal
*/
abstract onDestroy?(callback: () => void): void;
}

View File

@ -1,6 +1,5 @@
import { Location } from '@angular/common';
import {
ComponentFactoryResolver,
ComponentRef,
ElementRef,
Injector,
@ -8,24 +7,23 @@ import {
OnDestroy,
OnInit,
ViewContainerRef,
inject,
Attribute,
Directive,
EventEmitter,
Optional,
Output,
SkipSelf,
Input,
EnvironmentInjector,
} from '@angular/core';
import { OutletContext, Router, ActivatedRoute, ChildrenOutletContexts, PRIMARY_OUTLET } from '@angular/router';
import { OutletContext, Router, ActivatedRoute, ChildrenOutletContexts, PRIMARY_OUTLET, Data } from '@angular/router';
import { componentOnReady } from '@ionic/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { distinctUntilChanged, filter, switchMap } from 'rxjs/operators';
import { EnvironmentInjector } from '../../di/r3_injector';
import { AnimationBuilder } from '../../ionic-core';
import { Config } from '../../providers/config';
import { NavController } from '../../providers/nav-controller';
import { isComponentFactoryResolver } from '../../util/util';
import { StackController } from './stack-controller';
import { RouteView, getUrl } from './stack-utils';
@ -58,22 +56,20 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
tabsPrefix: string | undefined;
/**
* @experimental
*
* The `EnvironmentInjector` provider instance from the parent component.
* Required for using standalone components with `ion-router-outlet`.
*
* Will be deprecated and removed when Angular 13 support is dropped.
*/
@Input() environmentInjector: EnvironmentInjector;
@Output() stackEvents = new EventEmitter<any>();
// eslint-disable-next-line @angular-eslint/no-output-rename
@Output('activate') activateEvents = new EventEmitter<any>();
// eslint-disable-next-line @angular-eslint/no-output-rename
@Output('deactivate') deactivateEvents = new EventEmitter<any>();
private parentContexts = inject(ChildrenOutletContexts);
private location = inject(ViewContainerRef);
private environmentInjector = inject(EnvironmentInjector);
// Ionic providers
private config = inject(Config);
private navCtrl = inject(NavController);
set animation(animation: AnimationBuilder) {
this.nativeEl.animation = animation;
}
@ -95,13 +91,8 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
}
constructor(
private parentContexts: ChildrenOutletContexts,
private location: ViewContainerRef,
@Attribute('name') name: string,
@Optional() @Attribute('tabs') tabs: string,
private config: Config,
private navCtrl: NavController,
@Optional() private componentFactoryResolver: ComponentFactoryResolver,
commonLocation: Location,
elementRef: ElementRef,
router: Router,
@ -112,8 +103,8 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
this.nativeEl = elementRef.nativeElement;
this.name = name || PRIMARY_OUTLET;
this.tabsPrefix = tabs === 'true' ? getUrl(router, activatedRoute) : undefined;
this.stackCtrl = new StackController(this.tabsPrefix, this.nativeEl, router, navCtrl, zone, commonLocation);
parentContexts.onChildOutletCreated(this.name, this as any);
this.stackCtrl = new StackController(this.tabsPrefix, this.nativeEl, router, this.navCtrl, zone, commonLocation);
this.parentContexts.onChildOutletCreated(this.name, this as any);
}
ngOnDestroy(): void {
@ -125,12 +116,17 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
}
ngOnInit(): void {
this.initializeOutletWithName();
}
// Note: Ionic deviates from the Angular Router implementation here
private initializeOutletWithName() {
if (!this.activated) {
// If the outlet was not instantiated at the time the route got activated we need to populate
// the outlet when it is initialized (ie inside a NgIf)
const context = this.getContext();
if (context?.route) {
this.activateWith(context.route, context.resolver || null);
this.activateWith(context.route, context.injector);
}
}
@ -159,7 +155,7 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
return this._activatedRoute as ActivatedRoute;
}
get activatedRouteData(): any {
get activatedRouteData(): Data {
if (this._activatedRoute) {
return this._activatedRoute.snapshot.data;
}
@ -221,10 +217,7 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
}
}
activateWith(
activatedRoute: ActivatedRoute,
resolverOrInjector?: ComponentFactoryResolver | EnvironmentInjector | null
): void {
activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector | null): void {
if (this.isActivated) {
throw new Error('Cannot activate an already activated outlet');
}
@ -252,22 +245,6 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
* We check for the presence of this property to determine if the route is
* using standalone components.
*/
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (snapshot.routeConfig!.component == null && this.environmentInjector == null) {
console.warn(
'[Ionic Warning]: You must supply an environmentInjector to use standalone components with routing:\n\n' +
'In your component class, add:\n\n' +
` import { EnvironmentInjector } from '@angular/core';\n` +
' constructor(public environmentInjector: EnvironmentInjector) {}\n' +
'\n' +
'In your router outlet template, add:\n\n' +
' <ion-router-outlet [environmentInjector]="environmentInjector"></ion-router-outlet>\n\n' +
'Alternatively, if you are routing within ion-tabs:\n\n' +
' <ion-tabs [environmentInjector]="environmentInjector"></ion-tabs>'
);
return;
}
const childContexts = this.parentContexts.getOrCreateContext(this.name).children;
// We create an activated route proxy object that will maintain future updates for this component
@ -277,43 +254,15 @@ export class IonRouterOutlet implements OnDestroy, OnInit {
const injector = new OutletInjector(activatedRouteProxy, childContexts, this.location.injector);
/**
* The resolver is not always provided and is required in Angular 12.
* Fallback to the class-level provider when the resolver is not set.
*/
resolverOrInjector = resolverOrInjector || this.componentFactoryResolver;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const component = snapshot.routeConfig!.component ?? snapshot.component;
if (resolverOrInjector && isComponentFactoryResolver(resolverOrInjector)) {
// Backwards compatibility for Angular 13 and lower
const factory = resolverOrInjector.resolveComponentFactory(component);
cmpRef = this.activated = this.location.createComponent(factory, this.location.length, injector);
} else {
/**
* Angular 14 and higher.
*
* TODO: FW-1641: Migrate once Angular 13 support is dropped.
*
* When we drop < Angular 14, we can replace the following code with:
* ```ts
const environmentInjector = resolverOrInjector ?? this.environmentInjector;
cmpRef = this.activated = location.createComponent(component, {
index: location.length,
injector,
environmentInjector,
});
* ```
* where `this.environmentInjector` is a provider of `EnvironmentInjector` from @angular/core.
*/
const environmentInjector = resolverOrInjector ?? this.environmentInjector;
cmpRef = this.activated = this.location.createComponent(component, {
index: this.location.length,
injector,
environmentInjector,
} as any);
}
cmpRef = this.activated = this.location.createComponent(component, {
index: this.location.length,
injector,
environmentInjector: environmentInjector ?? this.environmentInjector,
});
// Once the component is created we can push it to our local subject supplied to the proxy
component$.next(cmpRef.instance);

View File

@ -1,6 +1,5 @@
import { Component, ContentChild, EventEmitter, HostListener, Input, Output, ViewChild } from '@angular/core';
import { Component, ContentChild, EventEmitter, HostListener, Output, ViewChild } from '@angular/core';
import { EnvironmentInjector } from '../../di/r3_injector';
import { NavController } from '../../providers/nav-controller';
import { IonTabBar } from '../proxies';
@ -11,12 +10,7 @@ import { StackEvent } from './stack-utils';
selector: 'ion-tabs',
template: ` <ng-content select="[slot=top]"></ng-content>
<div class="tabs-inner">
<ion-router-outlet
#outlet
tabs="true"
[environmentInjector]="environmentInjector"
(stackEvents)="onPageSelected($event)"
></ion-router-outlet>
<ion-router-outlet #outlet tabs="true" (stackEvents)="onPageSelected($event)"></ion-router-outlet>
</div>
<ng-content></ng-content>`,
styles: [
@ -52,16 +46,6 @@ export class IonTabs {
@ViewChild('outlet', { read: IonRouterOutlet, static: false }) outlet: IonRouterOutlet;
@ContentChild(IonTabBar, { static: false }) tabBar: IonTabBar | undefined;
/**
* @experimental
*
* The `EnvironmentInjector` provider instance from the parent component.
* Required for using standalone components with `ion-router-outlet`.
*
* Will be deprecated and removed when Angular 13 support is dropped.
*/
@Input() environmentInjector: EnvironmentInjector;
@Output() ionTabsWillChange = new EventEmitter<{ tab: string }>();
@Output() ionTabsDidChange = new EventEmitter<{ tab: string }>();

View File

@ -1,4 +1,4 @@
import { ComponentFactoryResolver, ElementRef, Injector, ViewContainerRef, Directive } from '@angular/core';
import { ElementRef, Injector, Directive, EnvironmentInjector } from '@angular/core';
import { AngularDelegate } from '../../providers/angular-delegate';
import { ProxyCmp, proxyOutputs } from '../angular-component-lib/utils';
@ -29,13 +29,12 @@ export class NavDelegate {
protected el: HTMLElement;
constructor(
ref: ElementRef,
resolver: ComponentFactoryResolver,
environmentInjector: EnvironmentInjector,
injector: Injector,
angularDelegate: AngularDelegate,
location: ViewContainerRef
angularDelegate: AngularDelegate
) {
this.el = ref.nativeElement;
ref.nativeElement.delegate = angularDelegate.create(resolver, injector, location);
ref.nativeElement.delegate = angularDelegate.create(environmentInjector, injector);
proxyOutputs(this, this.el, ['ionNavDidChange', 'ionNavWillChange']);
}
}

View File

@ -1,11 +1,12 @@
import {
ApplicationRef,
ComponentFactoryResolver,
NgZone,
ViewContainerRef,
Injectable,
InjectionToken,
Injector,
EnvironmentInjector,
inject,
createComponent,
InjectionToken,
ComponentRef,
} from '@angular/core';
import {
@ -17,27 +18,24 @@ import {
LIFECYCLE_WILL_UNLOAD,
} from '@ionic/core';
import { EnvironmentInjector } from '../di/r3_injector';
import { NavParams } from '../directives/navigation/nav-params';
import { isComponentFactoryResolver } from '../util/util';
// TODO(FW-2827): types
@Injectable()
export class AngularDelegate {
constructor(private zone: NgZone, private appRef: ApplicationRef) {}
private zone = inject(NgZone);
private applicationRef = inject(ApplicationRef);
create(
resolverOrInjector: ComponentFactoryResolver,
environmentInjector: EnvironmentInjector,
injector: Injector,
location?: ViewContainerRef,
elementReferenceKey?: string
): AngularFrameworkDelegate {
return new AngularFrameworkDelegate(
resolverOrInjector,
environmentInjector,
injector,
location,
this.appRef,
this.applicationRef,
this.zone,
elementReferenceKey
);
@ -45,14 +43,13 @@ export class AngularDelegate {
}
export class AngularFrameworkDelegate implements FrameworkDelegate {
private elRefMap = new WeakMap<HTMLElement, any>();
private elRefMap = new WeakMap<HTMLElement, ComponentRef<any>>();
private elEventsMap = new WeakMap<HTMLElement, () => void>();
constructor(
private resolverOrInjector: ComponentFactoryResolver | EnvironmentInjector,
private environmentInjector: EnvironmentInjector,
private injector: Injector,
private location: ViewContainerRef | undefined,
private appRef: ApplicationRef,
private applicationRef: ApplicationRef,
private zone: NgZone,
private elementReferenceKey?: string
) {}
@ -78,10 +75,9 @@ export class AngularFrameworkDelegate implements FrameworkDelegate {
const el = attachView(
this.zone,
this.resolverOrInjector,
this.environmentInjector,
this.injector,
this.location,
this.appRef,
this.applicationRef,
this.elRefMap,
this.elEventsMap,
container,
@ -115,40 +111,37 @@ export class AngularFrameworkDelegate implements FrameworkDelegate {
export const attachView = (
zone: NgZone,
resolverOrInjector: ComponentFactoryResolver | EnvironmentInjector,
environmentInjector: EnvironmentInjector,
injector: Injector,
location: ViewContainerRef | undefined,
appRef: ApplicationRef,
elRefMap: WeakMap<HTMLElement, any>,
applicationRef: ApplicationRef,
elRefMap: WeakMap<HTMLElement, ComponentRef<any>>,
elEventsMap: WeakMap<HTMLElement, () => void>,
container: any,
component: any,
params: any,
cssClasses: string[] | undefined
): any => {
let componentRef: ComponentRef<any>;
/**
* Wraps the injector with a custom injector that
* provides NavParams to the component.
*
* NavParams is a legacy feature from Ionic v3 that allows
* Angular developers to provide data to a component
* and access it by providing NavParams as a dependency
* in the constructor.
*
* The modern approach is to access the data directly
* from the component's class instance.
*/
const childInjector = Injector.create({
providers: getProviders(params),
parent: injector,
});
if (resolverOrInjector && isComponentFactoryResolver(resolverOrInjector)) {
// Angular 13 and lower
const factory = resolverOrInjector.resolveComponentFactory(component);
componentRef = location
? location.createComponent(factory, location.length, childInjector)
: factory.create(childInjector);
} else if (location) {
// Angular 14
const environmentInjector = resolverOrInjector;
componentRef = location.createComponent(component, {
index: location.indexOf,
injector: childInjector,
environmentInjector,
} as any);
} else {
return null;
}
const componentRef = createComponent<any>(component, {
environmentInjector,
elementInjector: childInjector,
});
const instance = componentRef.instance;
const hostElement = componentRef.location.nativeElement;
@ -156,17 +149,15 @@ export const attachView = (
Object.assign(instance, params);
}
if (cssClasses) {
for (const clazz of cssClasses) {
hostElement.classList.add(clazz);
for (const cssClass of cssClasses) {
hostElement.classList.add(cssClass);
}
}
const unbindEvents = bindLifecycleEvents(zone, instance, hostElement);
container.appendChild(hostElement);
if (!location) {
appRef.attachView(componentRef.hostView);
}
componentRef.changeDetectorRef.reattach();
applicationRef.attachView(componentRef.hostView);
elRefMap.set(hostElement, componentRef);
elEventsMap.set(hostElement, unbindEvents);
return hostElement;

View File

@ -1,32 +1,24 @@
import { ComponentFactoryResolver, Injector, Injectable, Optional } from '@angular/core';
import { Injector, Injectable, EnvironmentInjector, inject } from '@angular/core';
import { ModalOptions, modalController } from '@ionic/core';
import { EnvironmentInjector } from '../di/r3_injector';
import { OverlayBaseController } from '../util/overlay';
import { AngularDelegate } from './angular-delegate';
@Injectable()
export class ModalController extends OverlayBaseController<ModalOptions, HTMLIonModalElement> {
constructor(
private angularDelegate: AngularDelegate,
private resolver: ComponentFactoryResolver,
private injector: Injector,
// TODO: FW-1641: Migrate to Angular's version once Angular 13 is dropped
@Optional() private environmentInjector: EnvironmentInjector
) {
private angularDelegate = inject(AngularDelegate);
private injector = inject(Injector);
private environmentInjector = inject(EnvironmentInjector);
constructor() {
super(modalController);
}
create(opts: ModalOptions): Promise<HTMLIonModalElement> {
return super.create({
...opts,
delegate: this.angularDelegate.create(
this.resolver ?? this.environmentInjector,
this.injector,
undefined,
'modal'
),
delegate: this.angularDelegate.create(this.environmentInjector, this.injector, 'modal'),
});
}
}

View File

@ -262,10 +262,11 @@ const readQueryParam = (url: string, key: string) => {
};
const proxyEvent = <T>(emitter: Subject<T>, el: EventTarget, eventName: string) => {
if (el as any) {
el.addEventListener(eventName, (ev: Event | undefined | null) => {
if (el) {
el.addEventListener(eventName, (ev) => {
// ?? cordova might emit "null" events
emitter.next(ev != null ? ((ev as any).detail as T) : undefined);
const value = ev != null ? (ev as any).detail : undefined;
emitter.next(value);
});
}
};

View File

@ -1,32 +1,24 @@
import { ComponentFactoryResolver, Injector, Injectable, Optional } from '@angular/core';
import { Injector, Injectable, inject, EnvironmentInjector } from '@angular/core';
import { PopoverOptions, popoverController } from '@ionic/core';
import { EnvironmentInjector } from '../di/r3_injector';
import { OverlayBaseController } from '../util/overlay';
import { AngularDelegate } from './angular-delegate';
@Injectable()
export class PopoverController extends OverlayBaseController<PopoverOptions, HTMLIonPopoverElement> {
constructor(
private angularDelegate: AngularDelegate,
private resolver: ComponentFactoryResolver,
private injector: Injector,
// TODO: FW-1641: Migrate to Angular's version once Angular 13 is dropped
@Optional() private environmentInjector: EnvironmentInjector
) {
private angularDelegate = inject(AngularDelegate);
private injector = inject(Injector);
private environmentInjector = inject(EnvironmentInjector);
constructor() {
super(popoverController);
}
create(opts: PopoverOptions): Promise<HTMLIonPopoverElement> {
return super.create({
...opts,
delegate: this.angularDelegate.create(
this.resolver ?? this.environmentInjector,
this.injector,
undefined,
'popover'
),
delegate: this.angularDelegate.create(this.environmentInjector, this.injector, 'popover'),
});
}
}

View File

@ -332,7 +332,7 @@ export function getFirstNgModuleName(source: ts.SourceFile): string | undefined
// Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
// metadata.
const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
if (!moduleClass || !moduleClass.name) {
if (!moduleClass?.name) {
return undefined;
}

View File

@ -1,5 +1,3 @@
import { ComponentFactoryResolver } from '@angular/core';
declare const __zone_symbol__requestAnimationFrame: any;
declare const requestAnimationFrame: any;
@ -12,7 +10,3 @@ export const raf = (h: any): any => {
}
return setTimeout(h);
};
export const isComponentFactoryResolver = (item: any): item is ComponentFactoryResolver => {
return !!item.resolveComponentFactory;
};