{ "id": "guide/ivy-compatibility-examples", "title": "Ivy compatibility examples", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Ivy compatibility exampleslink

\n

This appendix is intended to provide more background on Ivy changes. Many of these examples list error messages you may see, so searching by error message might be a good idea if you are debugging.

\n
\nNOTE: Most of these issues affect a small percentage of applications encountering unusual or rare edge cases.\n
\n\n

@ContentChildren queries only match direct children by defaultlink

\n

Basic example of changelink

\n

Let's say a component (Comp) has a @ContentChildren query for 'foo':

\n\n<comp>\n <div>\n <div #foo></div> <!-- matches in old runtime, not in new runtime -->\n </div>\n</comp>\n\n

In the previous runtime, the <div> with #foo would match.\nWith Ivy, that <div> does not match because it is not a direct child of <comp>.

\n

Backgroundlink

\n

By default, @ContentChildren queries have the descendants flag set to false.

\n

In the previous rendering engine, \"descendants\" referred to \"descendant directives\".\nAn element could be a match as long as there were no other directives between the element and the requesting directive.\nThis made sense for directives with nesting like tabs, where nested tab directives might not be desirable to match.\nHowever, this caused surprising behavior for users because adding an unrelated directive like ngClass to a wrapper element could invalidate query results.

\n

For example, with the content query and template below, the last two Tab directives would not be matches:

\n\n@ContentChildren(Tab, {descendants: false}) tabs: QueryList<Tab>\n\n\n<tab-list>\n <div>\n <tab> One </tab> <!-- match (nested in element) -->\n </div>\n <tab> <!-- match (top level) -->\n <tab> A </tab> <!-- not a match (nested in tab) -->\n </tab>\n <div [ngClass]=\"classes\">\n <tab> Two </tab> <!-- not a match (nested in ngClass) -->\n </div>\n</tab-list>\n\n

In addition, the differences between type and string predicates were subtle and sometimes unclear.\nFor example, if you replace the type predicate above with a 'foo' string predicate, the matches change:

\n\n@ContentChildren('foo', {descendants: false}) foos: QueryList<ElementRef>\n\n\n<tab-list>\n <div>\n <div #foo> One </div> <!-- match (nested in element) -->\n </div>\n <tab #foo> <!-- match (top level) -->\n <div #foo> A </div> <!-- match (nested in tab) -->\n </tab>\n <div [ngClass]=\"classes\">\n <div #foo> Two </div> <!-- match (nested in ngClass) -->\n </div>\n</tab-list>\n\n

Because the previous behavior was inconsistent and surprising to users, we did not want to reproduce it in Ivy.\nInstead, we simplified the mental model so that \"descendants\" refers to DOM nesting only.\nAny DOM element between the requesting component and a potential match will invalidate that match.\nType predicates and string predicates also have identical matching behavior.

\n

Ivy behavior for directive/string predicates:

\n\n<tab-list>\n <div>\n <tab> One </tab> <!-- not a match (nested in element) -->\n </div>\n <tab> <!-- match (top level) -->\n <tab> A </tab> <!-- not a match (nested in tab) -->\n </tab>\n <div [ngClass]=\"classes\">\n <tab> Two </tab> <!-- not a match (nested in div) -->\n </div>\n</tab-list>\n\n

Example of errorlink

\n

The error message that you see will depend on how the particular content query is used in the application code.\nFrequently, an error is thrown when a property is referenced on the content query result (which is now undefined).

\n

For example, if the component sets the content query results to a property, foos, foos.first.bar would throw the error:

\n\nUncaught TypeError: Cannot read property 'bar' of undefined\n\n

If you see an error like this, and the undefined property refers to the result of a @ContentChildren query, it may well be caused by this change.

\n

Recommended fixlink

\n

You can either add the descendants: true flag to ignore wrapper elements or remove the wrapper elements themselves.

\n

Option 1:

\n\n@ContentChildren('foo', {descendants: true}) foos: QueryList<ElementRef>;\n\n

Option 2:

\n\n<comp>\n <div #foo></div> <!-- matches in both old runtime and new runtime -->\n</comp>\n\n\n

All classes that use Angular DI must have an Angular class-level decoratorlink

\n

Basic example of change:link

\n

In the previous rendering engine, the following would work:

\n\nexport class DataService {\n constructor(@Inject('CONFIG') public config: DataConfig) {}\n}\n\n@Injectable()\nexport class AppService extends DataService {...}\n\n

In Ivy, it will throw an error because DataService is using Angular dependency injection, but is missing an @Injectable decorator.

\n

The following would also work in the previous rendering engine, but in Ivy would require a @Directive decorator because it uses DI:

\n\nexport class BaseMenu {\n constructor(private vcr: ViewContainerRef) {}\n}\n\n@Directive({selector: '[settingsMenu]'})\nexport class SettingsMenu extends BaseMenu {}\n\n

The same is true if your directive class extends a decorated directive, but does not have a decorator of its own.

\n

If you're using the CLI, there are two automated migrations that should transition your code for you (this one and this one).\nHowever, as you're adding new code in version 9, you may run into this difference.

\n

Backgroundlink

\n

When a class has an Angular decorator like @Injectable or @Directive, the Angular compiler generates extra code to support injecting dependencies into the constructor of your class.\nWhen using inheritance, Ivy needs both the parent class and the child class to apply a decorator to generate the correct code.\nOtherwise, when the decorator is missing from the parent class, the subclass will inherit a constructor from a class for which the compiler did not generate special constructor info, and Angular won't have the dependency info it needs to create it properly.

\n

In the previous rendering engine, the compiler had global knowledge, so in some cases (such as AOT mode or the presence of certain injection flags), it could look up the missing data.\nHowever, the Ivy compiler only processes each class in isolation.\nThis means that compilation has the potential to be faster (and opens the framework up for optimizations and features going forward), but the compiler can't automatically infer the same information as before.

\n

Adding the proper decorator explicitly provides this information.

\n

Example of errorlink

\n

In JIT mode, the framework will throw the following error:

\n\nERROR: This constructor is not compatible with Angular Dependency Injection because its dependency at index X of the parameter list is invalid.\nThis can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.\n\nPlease check that 1) the type for the parameter at index X is correct and 2) the correct Angular decorators are defined for this class and its ancestors.\n\n

In AOT mode, you'll see something like:

\n\nX inherits its constructor from Y, but the latter does not have an Angular decorator of its own.\nDependency injection will not be able to resolve the parameters of Y's constructor. Either add a\n@Directive decorator to Y, or add an explicit constructor to X.\n\n

In some cases, the framework may not be able to detect the missing decorator.\nIn these cases, you'll generally see a runtime error thrown when there is a property access attempted on the missing dependency.\nIf dependency was foo, you'd see an error when accessing something like foo.bar:

\n\nUncaught TypeError: Cannot read property 'bar' of undefined\n\n

If you see an error like this, and the undefined value refers to something that should have been injected, it may be this change.

\n

Recommended fixlink

\n\n\n@Injectable()\nexport class DataService {\n constructor(@Inject('CONFIG') public config: DataConfig) {}\n}\n\n@Injectable()\nexport class AppService extends DataService {...}\n\n\n\n@Directive() // selectorless, so it's not usable directly\nexport class BaseMenu {\n constructor(private vcr: ViewContainerRef) {}\n}\n\n@Directive({selector: '[settingsMenu]'})\nexport class SettingsMenu extends BaseMenu {}\n\n\n

Cannot Bind to value property of <select> with *ngForlink

\n

Basic example of changelink

\n\n<select [value]=\"someValue\">\n <option *ngFor=\"let option of options\" [value]=\"option\"> {{ option }} <option>\n</select>\n\n

In the View Engine runtime, the above code would set the initial value of the <select> as expected.\nIn Ivy, the initial value would not be set at all in this case.

\n

Backgroundlink

\n

Prior to Ivy, directive input bindings were always executed in their own change detection pass before any DOM bindings were processed.\nThis was an implementation detail that supported the use case in question:

\n\n<select [value]=\"someValue\">\n <option *ngFor=\"let option of options\" [value]=\"option\"> {{ option }} <option>\n</select>\n\n

It happened to work because the *ngFor would be checked first, during the directive input binding pass, and thus create the options first.\nThen the DOM binding pass would run, which would check the value binding.\nAt this time, it would be able to match the value against one of the existing options, and set the value of the <select> element in the DOM to display that option.

\n

In Ivy, bindings are checked in the order they are defined in the template, regardless of whether they are directive input bindings or DOM bindings.\nThis change makes change detection easier to reason about for debugging purposes, since bindings will be checked in depth-first order as declared in the template.

\n

In this case, it means that the value binding will be checked before the *ngFor is checked, as it is declared above the *ngFor in the template.\nConsequently, the value of the <select> element will be set before any options are created, and it won't be able to match and display the correct option in the DOM.

\n

Example of errorlink

\n

There is no error thrown, but the <select> in question will not have the correct initial value displayed in the DOM.

\n

Recommended fixlink

\n

To fix this problem, we recommend binding to the selected property on the <option> instead of the value on the <select>.

\n

Before

\n\n<select [value]=\"someValue\">\n <option *ngFor=\"let option of options\" [value]=\"option\"> {{ option }} <option>\n</select>\n\n

After

\n\n<select>\n <option *ngFor=\"let option of options\" [value]=\"option\" [selected]=\"someValue == option\">\n {{ option }}\n <option>\n</select>\n\n\n

Forward references to directive inputs accessed through local refs are no longer supported.link

\n

Basic example of changelink

\n\n@Directive({\n selector: '[myDir]',\n exportAs: 'myDir'\n})\nexport class MyDir {\n @Input() message: string;\n}\n\n\n{{ myDir.name }}\n<div myDir #myDir=\"myDir\" [name]=\"myName\"></div>\n\n

In the View Engine runtime, the above code would print out the name without any errors.\nIn Ivy, the myDir.name binding will throw an ExpressionChangedAfterItHasBeenCheckedError.

\n

Backgroundlink

\n

In the ViewEngine runtime, directive input bindings and element bindings were executed in different stages. Angular would process the template one full time to check directive inputs only (e.g. [name]), then process the whole template again to check element and text bindings only (e.g.{{ myDir.name }}). This meant that the name directive input would be checked before the myDir.name text binding despite their relative order in the template, which some users felt to be counterintuitive.

\n

In contrast, Ivy processes the template in just one pass, so that bindings are checked in the same order that they are written in the template. In this case, it means that the myDir.name binding will be checked before the name input sets the property on the directive (and thus it will be undefined). Since the myDir.name property will be set by the time the next change detection pass runs, a change detection error is thrown.

\n

Example of errorlink

\n

Assuming that the value for myName is Angular, you should see an error that looks like

\n\nError: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Angular'.\n\n

Recommended fixlink

\n

To fix this problem, we recommend either getting the information for the binding directly from the host component (e.g. the myName property from our example) or to move the data binding after the directive has been declared so that the initial value is available on the first pass.

\n

Before

\n\n{{ myDir.name }}\n<div myDir #myDir=\"myDir\" [name]=\"myName\"></div>\n\n

After

\n\n{{ myName }}\n<div myDir [name]=\"myName\"></div>\n\n\n

Foreign functions and foreign values aren't statically resolvablelink

\n

Basic example of changelink

\n

Consider a library that defines and exports some selector string to be used in other libraries:

\n\nexport let mySelector = '[my-selector]';\n\n

This selector is then imported in another library or an application:

\n\nimport {mySelector} from 'my-library';\n\n@Directive({selector: mySelector})\nexport class MyDirective {}\n\n

Because the mySelector value is imported from an external library, it is part of a different compilation unit and therefore considered foreign.

\n

While this code would work correctly in the View Engine compiler, it would fail to compile in Ivy in AOT mode.

\n

Backgroundlink

\n

In View Engine, the compiler would capture the source code of a library in metadata.json files when bundling the library, so that external consumers could \"look inside\" the source code of an external library.\nWhen AOT-compiling the application, the metadata.json files would be used to determine the value of mySelector.\nIn Ivy, the metadata.json files are no longer used. Instead, the compiler extracts metadata for external libraries from the .d.ts files that TypeScript creates.\nThis has several benefits such as better performance, much improved error reporting, and enables more build caching opportunities as there is no longer a dependency on library internals.

\n

Looking back at the previous example, the mySelector value would be represented in the .d.ts as follows:

\n\nexport declare let mySelector: string;\n\n

Notice that the actual value of the selector is no longer present, so that the Ivy compiler is unable to use it during AOT compilations.

\n

Example of errorlink

\n

In the above example, a compilation error would occur when compiling MyDirective:

\n\nerror NG1010: selector must be a string\n Value is a reference to 'mySelector'.\n\n 1 export declare let mySelector: string;\n ~~~~~~~~~~\n Reference is declared here.\n\n

Recommended fixlink

\n

When exporting values from a library, ensure the actual value is present in the .d.ts file. This typically requires that the variable be declared as a constant:

\n\nexport const mySelector = '[my-selector]';\n\n

In classes, a field should be declared using the static readonly modifiers:

\n\nexport class Selectors {\n static readonly mySelector = '[my-selector]';\n}\n\n\n \n
\n\n\n" }