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

В зависимости от значения (логической) переменной класса, я хотел бы мой 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 {}

3 ответа

Решение

Угловой ^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>

Пример поршня угловой v4

Угловой < 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);
      }
    }
  }
}

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

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>

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

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

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

Другие вопросы по тегам