Kesem David Kesem David - 1 month ago 44x
AngularJS Question

Angular2 Child Component with OPTIONAL Input

TLDR: Can an
be optional?

So i have this child component which is a modal for creating a Transaction (in bank terms), and i want to upgrade this modal to be create-or-update Transaction.

Currently the modal is just a group of input fields and a submit button for creating.
What i want to achieve is when this component gets a transaction as an input, it will be on 'edit-mode' and when it does not it will be on 'create-mode' (meaning the input field will be already filled with data in edit-mode and empty on create-mode)

Can an
@Input transaction
somehow be optional?


Yes. Even more, simply do this in case you want changes

<div *ngIf="transaction">Some edit stuff</div>
<div *ngIf="!transaction">Create stuff</div>

If you want specific stuff

ngOnInit() {
  if(!this.transaction) { 
    // create stuff only 
  } else {
    // update stuff only

EDIT: how I would do it (in your case)

This may not be the best solution, but should work (if I didn't get the syntax wrong)

ngOnInit() {
  if(!this.transaction) { 
    this.transaction = new Transaction();

this way all class properties will be available, only empty. Unless you want them predefined, you can set them in a constructor, or in ngOnInit.