取决于(布尔)类变量的值,我希望我的ng-content要么包含在div中,要么不包含在div中(即div甚至不应该在DOM中)…什么是最好的这个怎么样?我有一个
Plunker试图做到这一点,我认为是最明显的方式,使用ngIf ..但它不工作…它只显示其中一个布尔值的内容,但不显示另一个
善意的协助
谢谢!
@L_502_1@
@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 {}
Angular ^ 4
原文链接:https://www.f2er.com/angularjs/143880.html<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>
角度< 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); } } } }