简体   繁体   中英

Angular change the wrapper for a component conditionally

I have a component where the HTML is like this:

<app-cancel-apply (onApply)="onApply()" (onCancel)="onCancel()">
  <!-- 100+ lines of HTML here -->
</app-cancel-apply>

But depending on a boolean @Input flag named okOnly sometimes I want:

<app-ok (onOk)="onCancel()">
  <!-- The exact same 100+ lines of HTML here -->
</app-ok>

How can I conditionally change the outer wrapper without creating a new component and copying and pasting the 100+ lines of HTML? Thanks

I'm thinking I could use content projection (could be wrong) but I'm already using content projection to project the 100+ lines of HTML. Doing it twice seems crazy.

You can define a common template for the inner content:

<ng-template #innerContent>
  <!-- 100+ lines of HTML here -->
</ng-template>

And insert it with a template outlet in the appropriate container, which can be set with ngIf...else :

<app-ok *ngIf="okOnly; else cancelTemplate" (onOk)="onCancel()">
  <ng-container *ngTemplateOutlet="innerContent"></ng-container>
</app-ok>

<ng-template #cancelTemplate>
  <app-cancel-apply (onApply)="onApply()" (onCancel)="onCancel()">
    <ng-container *ngTemplateOutlet="innerContent"></ng-container>
  </app-cancel-apply>
</ng-template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM