Search code examples
angularerror-handlingpropertiesangular-ng-if

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


ex) post_no=1, click the EDIT button.

An error occurs.

error: Can not read property 'edit' of undefined.

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

Using two ngIf seems to cause an property error. (editor_edit.edit())

Is there a good solution?

Other ways that do not use two ngIfs is okay.


Solution

  • use hidden attribute, It will help to keep DOM present.

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

    here's the Stackblitz demo.