Angular中模板引用变量的范围是什么?

What is the scope of the template reference variable in Angular?

Angular中模板引用变量的范围是什么?

我在文档中找不到我的问题的明确答案。尽管凭经验我可以说整个模板都可以访问模板引用变量。

1是这样吗?模板引用变量是否保证在整个模板中都可以访问?

2 还是模板引用变量只能在模板引用变量引用的元素的子元素和兄弟元素中访问?

超过 here 我发现了以下语句:

Use template variables to refer to elements — The newHero template variable refers to the <input> element. You can reference newHero from any sibling or child of the <input> element.

是不是说只有2是Angular保证的?

如前所述here:

You can refer to a template reference variable anywhere in the component's template.

只要 DOM.

中存在相应的元素,就可以从模板中的任何位置访问模板引用变量

例如。如果尚未呈现,则无法访问 <ng-template> 元素内的模板引用变量。

<ng-template #templateOne let-message let-showAdditional="show">
  <div #templateDiv>
    One <br />
  </div>
</ng-template>

<ng-container *ngIf="templateDiv">
  Got template div
</ng-container>

这里Angular会报错

Property 'templateDiv' does not exist on type 'SomeComponent'.

因为变量引用的元素不存在于DOM中。


关于你的第 2 点。

You can reference newHero from any sibling or child of the element.

他们指的是具体教程。注意它没有说

You can reference newHero only from any sibling or child of the element.