principletypescriptangularCritical
<ng-container> vs <template>
Viewed 0 times
templatecontainerstackoverflow
Problem
ng-container is mentioned in the official documentation but I'm still trying to understand how it works and what are use cases.It is particularly mentioned in
ngPlural and ngSwitch directives.Does `
do the same thing as or does it depend on whether a directive was written to use one of them?
Are
there is nothing
and
there is nothing
supposed to be the same?
How do we choose one of them?
How can ` be used in a custom directive?Solution
Edit : Now it is documented
`
will then produce :
`
to the rescue
The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
(...)
The is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:
if (someCondition) {
statement1;
statement2;
statement3;
}
Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The satisfies a similar need in Angular templates.
Original answer:
According to this pull request :
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.
is rendered as an HTML comment.
so this angular template :
foo
will produce this kind of output :
foo
So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo"`) in your application but don't want to wrap them with another element.
Title
Content
will then produce :
Title
Content
Code Snippets
if (someCondition) {
statement1;
statement2;
statement3;
}<div>
<ng-container>foo</ng-container>
<div><div>
<!--template bindings={}-->foo
<div><div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div><div>
<h2>Title</h2>
<div>Content</div>
</div>Context
Stack Overflow Q#39547858, score: 315
Revisions (0)
No revisions yet.