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

时间:2018-08-29 06:22:36

标签: angular error-handling properties ngif

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的方法也可以。

2 个答案:

答案 0 :(得分:1)

使用隐藏属性,这将有助于保持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演示。

答案 1 :(得分:0)

* NgIf从DOM中删除组件。因此,您无法像以前那样访问组件。

您也可以使用[hidden]属性,该属性使用“ display:none” css属性。