按条件将TemplateRef替换为TemplateRef

问题描述 投票:0回答:1

如果ElementRef评估为loadingButtonTemplate,我想用模板loading替换作为true传递的按钮。我怎么能做到这一点?如果loading回到false,它应该反过来反之亦然。

APP-form.component.ts:

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html'
})
export class FormComponent {

  @Input()
  submitButton: ElementRef;

  @Input()
  loading: boolean;

  @ViewChild('loadingButtonTemplate')
  private loadingButtonTemplate: TemplateRef<any>;

  constructor() {
  }

}

APP-form.component.html:

<form [formGroup]="formGroup" (ngSubmit)="submit()" autocomplete="off" novalidate>
  <ng-content></ng-content>
</form>

<ng-template #loadingButtonTemplate>
  <button loadingButton></button> <!-- third party directive -->
</ng-template>

所需用法:

<app-form [submitButton]="submitButton" [loading]="loading">

  ... some form inputs ...

  <button type="button">Delete</button>
  <button #submitButton type="submit">Add</button>

</app-form>

另一种更好的方法是将指令和所需的类“注入”按钮而不是替换它吗?

angular
1个回答
0
投票

您可以使用* ngIf和其他方式实现此目的。

<app-form [submitButton]="submitButton" [loading]="loading">

  ... some form inputs ...

  <button type="button">Delete</button>
  <button #submitButton *ngIf="!loading;else loadingButtonTemplate" type="submit">Add</button>

</app-form>

<ng-template #loadingButtonTemplate>
  <button loadingButton></button> <!-- third party directive -->
</ng-template>
© www.soinside.com 2019 - 2024. All rights reserved.