简体   繁体   English

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

[英]What is the scope of the template reference variable in Angular?

What is the scope of the template reference variable in Angular? Angular中模板引用变量的scope是什么?

I can not find a clear answer to my question in documentation.我在文档中找不到我的问题的明确答案。 Even though empirically I can say that the whole template can access the template reference variable.尽管凭经验我可以说整个模板都可以访问模板引用变量。

1 Is it the case? 1是这样吗? Is the template reference variable guaranteed to be accessible in the whole template?模板引用变量是否保证可以在整个模板中访问?

2 Or is the template reference variable accessible only in the child and sibling elements of the element which is referenced by the template reference variable? 2或者模板引用变量只能在模板引用变量引用的元素的子元素和兄弟元素中访问?

Over here I found the following statement:这里,我发现了以下声明:

Use template variables to refer to elements — The newHero template variable refers to the <input> element.使用模板变量引用元素 — newHero模板变量引用<input>元素。 You can reference newHero from any sibling or child of the <input> element.您可以从<input>元素的任何同级或子级引用newHero

Does it mean that only the 2 is guaranteed by Angular?是不是说Angular只保证2个?

Template reference variable could be accessed from anywhere in the template as long as the corresponding element is present in the DOM .只要 DOM 中存在相应的元素,就可以从模板中的任何位置访问模板引用变量。

For eg.例如。 you cannot access a template ref variable inside an <ng-template> element if it is not yet rendered.如果<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>

Here Angular will throw an error这里Angular会抛出错误

Property 'templateDiv' does not exist on type 'SomeComponent'. “SomeComponent”类型上不存在属性“templateDiv”。

because the element that is referenced by the variable is not present in the DOM.因为变量引用的元素在 DOM 中不存在。


Regarding your point 2.关于你的第2点。

You can reference newHero from any sibling or child of the element.您可以从元素的任何同级或子级引用newHero

They were referring to the specific tutorial.他们指的是具体的教程。 Notice it didn't say注意没有说

You can reference newHero only from any sibling or child of the element. 只能 从元素的任何同级或子级引用newHero

As stated here :如此所述:

You can refer to a template reference variable anywhere in the component's template.您可以在组件模板中的任何位置引用模板引用变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM