Angular 中模板引用变量的作用域是什么?
我在文档中找不到我的问题的明确答案。尽管凭经验我可以说整个模板都可以访问模板引用变量。
1 是这样吗?模板引用变量是否保证可以在整个模板中访问?
2 或者模板引用变量是否只能在模板引用变量引用的元素的子元素和同级元素中访问?
过 here我发现了以下声明:
Use template variables to refer to elements — The
newHero
template variable refers to the<input>
element. You can referencenewHero
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
onlyfrom any sibling or child of the element.
关于angular - Angular 中模板引用变量的作用域是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62213274/