You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Which @angular/* package(s) are relevant/related to the feature request?
core
Description
I would like to call setInput in my tests type-safely. I have recently migrated to OnPush, and found that setting properties directly on the input (component.myInput = newValue; fixture.detectChanges()) does not trigger change detection. Instead, I found two alternatives:
№ 2 adds boilerplate, and will not work with signals. Therefore № 1 is preferable. However, it does not offer any typesafety.
Proposed solution
The following type signature for setInput:
abstractclassComponentRef<C>{abstractsetInput<KextendsMutableKeys<C>>(name: K,value: C[K]): void;}typeMutableKeys<T>={[PinkeyofT]-?:
// Check if trying to assign a value to the property P after it's been initialized// does not result in a type error (indicating it's mutable). If it's mutable, include the key P.// We use a conditional type here, where we try to assign a different type to the property P// and check if it's assignable to the original type T. If it is, it means the property is mutable.IfEquals<{[QinP]: T[P]},{-readonly[QinP]: T[P]},P>}[keyofT];// Utility type to check if two types are exactly the sametypeIfEquals<X,Y,A=X,B=never>=(<T>()=>TextendsX ? 1 : 2)extends(<T>()=>TextendsY ? 1 : 2) ? A : B;
Sample usage:
classX{readonlya=1;b=2;c?: number;protectedd=4;privatee=5;}declareletcomponentRef: ComponentRef<X>;// @ts-expect-error - a is readonlycomponentRef.setInput("a",1);// b is mutablecomponentRef.setInput("b",2);// c is mutable and optionalcomponentRef.setInput("c",3);componentRef.setInput("c",undefined);// @ts-expect-error - d is protectedcomponentRef.setInput("d",4);// @ts-expect-error - e is protectedcomponentRef.setInput("e",5);
Which @angular/* package(s) are relevant/related to the feature request?
core
Description
I would like to call setInput in my tests type-safely. I have recently migrated to OnPush, and found that setting properties directly on the input (
component.myInput = newValue; fixture.detectChanges()
) does not trigger change detection. Instead, I found two alternatives:fixture.componentRef.setInput('myInput', newValue)
component.myInput = newValue; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges()
.№ 2 adds boilerplate, and will not work with signals. Therefore № 1 is preferable. However, it does not offer any typesafety.
Proposed solution
The following type signature for setInput:
Sample usage:
Typescript Playground
Open points:
Alternatives considered
component.myInput = newValue; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges()
The text was updated successfully, but these errors were encountered: