angular-docs-cn/packages/compiler
Kristiyan Kostadinov cdf1ea1951 refactor(compiler): retrieve variables from context inside nested template listener (#40833)
This is a pre-requisite for #40360. Given the following template which has a listener
that references a variable from a parent template (`name`):

```
<ng-template let-name="name">
  <button (click)="hello(name)"></button>
</ng-template>
```

We generate code that looks that looks like. Note how we access `name` through `ctx`:

```js
function template(rf, ctx) {
  if (rf & 1) {
    const r0 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "button", 2);
    ɵɵlistener("click", function() {
      ɵɵrestoreView(r0);
      const name_r0 = ctx.name; // Note the `ctx.name` access here.
      const ctx_r1 = ɵɵnextContext();
      return ctx_r1.log(name_r0);
    });
    ɵɵelementEnd();
  }
}
```

This works fine at the moment, because the template context object can't be changed after creation.
The changes in #40360 allow for the object to be changed, which means that the `ctx` reference
inside the listener will be out of date, because it was bound during creation mode.

This PR aims to address the issue by accessing the context inside listeners through the saved
view reference. With the new code, the generated code from above will look as follows:

```js
function template(rf, ctx) {
  if (rf & 1) {
    const r0 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "button", 2);
    ɵɵlistener("click", function() {
      const restoredCtx = ɵɵrestoreView(r0);
      const name_r0 = restoredCtx.name;
      const ctx_r1 = ɵɵnextContext();
      return ctx_r1.log(name_r0);
    });
    ɵɵelementEnd();
  }
}
```

PR Close #40833
2021-02-17 11:45:46 -08:00
..
design docs: fix grammatical errors and typos (#38868) 2020-10-27 13:18:01 -07:00
src refactor(compiler): retrieve variables from context inside nested template listener (#40833) 2021-02-17 11:45:46 -08:00
test fix(compiler): support multiple selectors in `:host-context()` (#40494) 2021-02-16 08:41:19 -08:00
testing build: update license headers to reference Google LLC (#37205) 2020-05-26 14:26:58 -04:00
BUILD.bazel build: add npm_integration_test && angular_integration_test (#33927) 2020-02-24 08:59:18 -08:00
compiler.ts build: update license headers to reference Google LLC (#37205) 2020-05-26 14:26:58 -04:00
index.ts build: update license headers to reference Google LLC (#37205) 2020-05-26 14:26:58 -04:00
package.json Revert "build: remove wombot proxy registry from package.jsons for release (#37378)" (#37495) 2020-06-10 08:21:45 -07:00
public_api.ts build: update license headers to reference Google LLC (#37205) 2020-05-26 14:26:58 -04:00