Jan
Jan

Reputation: 1318

ngIf only for _this_ element, show childs anyway

I know the phrasing of my question might be a little weird, but here is what I want:

I have a div, that I want to wrap around an input, but only when divIsNeeded. I always want to show the input field.

going through the documentation, I couldn't find anything. Is there any way to do it?

<!-- this should only be there if I actually need it, otherwise I don't want this div -->
<div *ngIf="needsInputGroup" class="input-group">
  <!-- this should always be visible -->
  <input type="text" placeholder="bla" />
</div>

Upvotes: 2

Views: 88

Answers (2)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

What Günter suggests in his answer works, but you have to specify the children twice. Instead, you can take leverage of <ng-template> element to specify the children only once. In this specific case it's not a problem because the element is rather simple, but what if the contents are larger?

Contents of <ng-template> will not be rendered where placed, but will instead be sort of like a definition of a light-weight component. Once placed somewhere, it will render, but not before. Another analogy for ng-template would be a function: you define it, but you won't get the result before you call it.

So anywhere in our template, we can define the inner contents. We give it a reference #children, which we will use later to render the template elsewhere.

<ng-template #children>
  <input type=text placeholder=bla>
</ng-template>

Now we render different things depending on the condition. We render the template by passing its reference (the name we've given it) to the structural directive ngTemplateOutlet.

<ng-container *ngIf="needsInputGroup">
  <div class="input-group">
    <ng-container *ngTemplateOutlet="children"></ng-container>
  </div>
</ng-container>

<ng-container *ngIf="!needsInputGroup">
  <ng-container *ngTemplateOutlet="children"></ng-container>
</ng-container>

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657376

<div *ngIf="needsInputGroup" class="input-group">
  <input type="text" placeholder="bla" />
</div>
<input *ngIf="!needsInputGroup" type="text" placeholder="bla" />

You can create a custom component that does that for you and reuse it everywhere. I don't think there is another way. But a custom component adds another element around the content

Upvotes: 1

Related Questions