angular |当我使用 2 ngIf 时,如何读取子组件的 属性?

angular | when I use 2 ngIf, how to read property of child component?

ex) post_no=1,单击“编辑”按钮。

发生错误。

错误:无法读取未定义的 属性 'edit'。

...
<app-editor *ngIf="!post_no" #editor_save></app-editor>
<app-editor *ngIf="post_no" #editor_edit></app-editor>
...
<div *ngIf="post_no; else notEdit">
    <button class="post-save-btn" (click)="editor_edit.edit()">EDIT</button>
  </div>
  <ng-template #notEdit>
    <button class="post-save-btn" (click)="editor_save.save()">SAVE</button>
  </ng-template>
</div>

使用两个 ngIf 似乎会导致 属性 错误。 (editor_edit.edit())

有什么好的解决方法吗?

其他不使用两个ngIf的方式也可以。

使用隐藏属性,这将有助于保持 DOM 存在。

<app-editor [hidden]="post_no" #editor_save></app-editor>
<app-editor [hidden]="!post_no" #editor_edit></app-editor>
...
<div *ngIf="post_no; else notEdit">
    <button class="post-save-btn" (click)="editor_edit.edit()">EDIT</button>
  </div>
  <ng-template #notEdit>
    <button class="post-save-btn" (click)="editor_save.save()">SAVE</button>
  </ng-template>
</div>

这是 Stackblitz 演示。

*NgIf 从 DOM 中删除组件。所以你不能像以前那样访问组件。

作为替代方案,您可以使用 [hidden] 属性,它使用 "display: none" css 属性.