6

TLDR: Can an @Input 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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

What i don't want to happen in my template is having double elements, i simply want the <input> to be filled with data or not, therefore I wanted to work with an optional @Input , you said it is possible, how can i achieve it then?
I edited. I really don't know if this is a good solution, but something like this works for me
I see, so that way I'll be able to place a <create-update-transaction [transaction]="this.transaction></create-update-transaction as well as <create-update-transaction></create-update-transaction>?
That's the idea
So i've had success with what you have suggested, only i did not check the input in the constructor and initialized the Input on the property declaration like this: @Input() transaction: Transaction = new Transaction() , it works fine, thanks alot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.