angular - Angular 中模板引用变量的作用域是什么?

标签 angular templates variables scope

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 保证吗?

最佳答案

只要 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.

关于angular - Angular 中模板引用变量的作用域是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62213274/

相关文章:

c++ - 当我将运算符重载为模板时会发生什么?

java - "p"无法解析为变量

javascript - 如何在 Angular 4 规范文件中模拟 nativeElement.focus()

angular - 以 Angular 显示事件选项卡

c++ - 如果 "struct"和 "class"是同一件事,那么为什么在 template<class T> 中只使用 "class"而不是 "struct"?

c++ - 二叉堆无匹配函数错误

java - Java中变量的默认值

Android Studio 终端 : Command not found

testing - Angular2 测试 - 未检测到变化

Angular 2 单元测试服务 stub 值不会改变?