[英]Should I use Angular ngIf directly on component
I'm new to Angular and getting used to the basics. 我是Angular的新手,已经习惯了基础知识。
If I have a component that I want to show or hide depending on a variable should I have the *ngIf on the component itself or the contents inside the component. 如果我有要根据变量显示或隐藏的组件,则应在组件本身或组件内部的内容上带有* ngIf。
Eg.1 The Component 'photos' component will load if the variable photos is true 例如1如果可变的照片为true,则将加载“照片”组件
<photos *ngIf="photos"></photos>
Eg.2 Contents of the component The photos component is always there but the contents are loaded 例如,组件2的内容照片组件始终存在,但是内容已加载
<section class="photos-content" *ngIf="photos"> // content here </section>
If you are using *ngIf
directive on html elements (eg. 2), so this element will be created in DOM. 如果您对html元素(例如2)使用
*ngIf
指令,那么将在DOM中创建此元素。 This is not so good by too much html elements. 过多的html元素并不是很好。 You page will be slow.
您的页面会很慢。 So the first example (eg. 1) is better.
因此,第一个示例(例如1)更好。
Otherwise you can extend your second example by using <ng-container></ng-container>
like this: 否则,您可以像下面这样使用
<ng-container></ng-container>
扩展第二个示例:
<ng-container *ngIf="photos">
<section class="photos-content">
// content here
</section>
</ng-container>
ng-container
isn't displayed in DOM. ng-container
未在DOM中显示。
More explonation about ng-container
you can find on this good answer and here is a short summary: 您可以在这个好答案中找到有关
ng-container
更多说明,这里是一个简短的摘要:
<ng-container>
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.<ng-container>
是一个逻辑容器,可用于对节点进行分组,但不能在DOM树中作为节点呈现。
<ng-container>
is rendered as an HTML comment.<ng-container>
呈现为HTML注释。
Here is an example 这是一个例子
This angular code: 此角度代码:
<div>
<ng-container>fooText</ng-container>
<div>
will produce this comment in your html file: 将在您的html文件中产生此注释:
<div>
<!--template bindings={}-->fooText
<div>
Read more about ng-container
here . 在此处阅读有关
ng-container
更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.