Как условно обернуть div вокруг ng-контента

в зависимости от значения переменной класса (булево), я хотел бы, чтобы мой ng-content либо был завернут в div, либо не был обернут в div (т.е. div не должен быть даже в DOM)... Каков наилучший способ сделать это? У меня есть Plunker, который пытается это сделать, в том, что я предполагал, был наиболее очевидным способом, используя ngIf.. но он не работает... Он отображает контент только для одного из булевых значений, но не для других

любезно помочь Спасибо!

http://plnkr.co/edit/omqLK0mKUIzqkkR3lQh8

@Component({
  selector: 'my-component',
  template: `

   <div *ngIf="insideRedDiv" style="display: inline; border: 1px red solid">
      <ng-content *ngIf="insideRedDiv"  ></ng-content> 
   </div>

   <ng-content *ngIf="!insideRedDiv"></ng-content>     

  `,
})
export class MyComponent {
  insideRedDiv: boolean = true;
}


@Component({
  template: `
    <my-component> ... "Here is the Content"  ... </my-component>
  `
})
export class App {}

Ответы

Ответ 1

Angular ^ 4

В качестве обходного решения я могу предложить вам следующее решение:

<div *ngIf="insideRedDiv; else elseTpl" style="display: inline; border: 1px red solid">
  <ng-container *ngTemplateOutlet="elseTpl"></ng-container>
</div>

<ng-template #elseTpl><ng-content></ng-content> </ng-template>

Пример плунжера angular v4

Angular < 4

Здесь вы можете создать специальную директиву, которая будет делать то же самое:

<div *ngIf4="insideRedDiv; else elseTpl" style="display: inline; border: 1px red solid">
   <ng-container *ngTemplateOutlet="elseTpl"></ng-container>
</div>

<template #elseTpl><ng-content></ng-content></template>

Пример плунжера

ngIf4.ts

class NgIfContext { public $implicit: any = null; }

@Directive({ selector: '[ngIf4]' })
export class NgIf4 {
  private context: NgIfContext = new NgIfContext();
  private elseTemplateRef: TemplateRef<NgIfContext>;
  private elseViewRef: EmbeddedViewRef<NgIfContext>;
  private viewRef: EmbeddedViewRef<NgIfContext>;

  constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgIfContext>) { }

  @Input()
  set ngIf4(condition: any) {
    this.context.$implicit = condition;
    this._updateView();
  }

  @Input()
  set ngIf4Else(templateRef: TemplateRef<NgIfContext>) {
    this.elseTemplateRef = templateRef;
    this.elseViewRef = null;
    this._updateView();
  }

  private _updateView() {
    if (this.context.$implicit) {
      this.viewContainer.clear();
      this.elseViewRef = null;

      if (this.templateRef) {
        this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef, this.context);
      }
    } else {
      if (this.elseViewRef) return;

      this.viewContainer.clear();
      this.viewRef = null;

      if (this.elseTemplateRef) {
        this.elseViewRef = this.viewContainer.createEmbeddedView(this.elseTemplateRef, this.context);
      }
    }
  }
}

Ответ 2

Я проверил это и обнаружил открытую проблему по поводу множественных переходов с тегом. Это не позволяет вам определять несколько тегов в одном файле шаблона.

Это объясняет, почему контент отображается корректно только тогда, когда другой тег удален в вашем примере plunker.

Вы можете увидеть открытую проблему здесь: https://github.com/angular/angular/issues/7795

Ответ 3

Помните, что вы можете поместить всю эту логику в отдельный компонент! (на основе ответа yurzui):

import { Component, Input } from '@angular/core';

@Component({
    selector: 'div-wrapper',
    template: `
    <div *ngIf="wrap; else unwrapped">
      <ng-content *ngTemplateOutlet="unwrapped">
      </ng-content>
    </div>
    <ng-template #unwrapped>
      <ng-content>
      </ng-content>
    </ng-template>
    `,
})
export class ConditionalDivComponent {
  @Input()
  public wrap = false;
}

Затем вы можете использовать его следующим образом:

<div-wrapper [wrap]="'true'">
 Hello world!        
</div-wrapper>