如何有条件地删除包装 div 并保留其子级?



我想制作一个名为showWrapperIf的结构指令,它要么保留整个元素和它所在的子元素,要么,当条件true时,删除它所在的元素(包装器(,并获取所有子元素并将其保存在 DOM 中。

所以,这个的结果

<div *showWrapperIf="true">
<h2></h2>
<p></p>
<any-component></any-component>
</div>

<div>
<h2></h2>
<p></p>
<any-component></any-component>
</div>

但是,如果conditionfalse,则只需要显示子项。例如:

<h2></h2>
<p></p>
<any-component></any-component>

堆栈闪电战演示

我知道我可以用<ng-template>*ngIf来做到这一点,但是包装器有很多子级,它会使文件的大小加倍并使其可读性降低。

这种方法似乎太复杂了,因为您的内容还包含您自己的组件。相反,您可以将此逻辑移动到单独的组件,这将使您的代码简洁明了。创建一个组件,比如conditional-wrapper,并将其添加到模块中。在组件中,只需放置一个基本Input即可接受来自父级的wrapperElement

@Input() wrapperElement: boolean;

在模板中,只需添加代码即可使用ngSwitch有条件地将任何element显示为包装器或不将包装器显示为默认值。

<ng-container [ngSwitch]="wrapperElement">
<div *ngSwitchCase="'div'">
<ng-container *ngTemplateOutlet="noWrapper"></ng-container>
</div>
<h2 *ngSwitchCase="'h2'">
<ng-container *ngTemplateOutlet="noWrapper"></ng-container>
</h2>
<ng-container *ngSwitchDefault>
<ng-container *ngTemplateOutlet="noWrapper"></ng-container>
</ng-container>
</ng-container>
<ng-template #noWrapper>
<ng-content></ng-content>
</ng-template>

现在,您需要做的就是递归显示父组件中的conditional-wrapperng-content将显示父组件中的数据投影到子组件。

<conditional-wrapper [wrapperElement]="condition ? 'div': ''">
<h2>Child 1</h2>
<p>Child 2</p>
<footer>Child 3</footer>
<conditional-wrapper [wrapperElement]="condition ? 'div': ''">
<p>Nested Child 4</p>
</conditional-wrapper>
</conditional-wrapper>

这是StackBlitz上的一个工作示例。

我认为你不能这样做。请注意,当有据可查的角度方式不够时,您可能会走向错误的方向!

无论如何,可能接近您需要的东西(我认为(是在主机元素上添加一个类!

您可以按如下方式执行此操作

this.viewContainer.clear();
this.viewContainer.createEmbeddedView(this.templateRef);
if (this.condition) {
const elementRef = (this.viewContainer.get(0) as any)
.rootNodes[0] as ElementRef;
this.renderer.addClass(elementRef, "myclass");
}

斯塔克闪电战

你可以用CSS做剩下的事情

最新更新