【问题标题】:Replace ElementRef with a TemplateRef by condition按条件将 ElementRef 替换为 TemplateRef
【发布时间】:2018-05-28 07:58:37
【问题描述】:

如果loading 的计算结果为true,我想用模板loadingButtonTemplate 替换作为ElementRef 传递的按钮。我怎样才能做到这一点?如果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】:

    您可以使用 *ngIf 和 else 来实现。

    <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>
    

    【讨论】:

      猜你喜欢
      • 2017-12-09
      • 2019-04-21
      • 2018-05-17
      • 2013-07-15
      • 1970-01-01
      • 2018-03-20
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多