Search code examples
angulartypescriptangular9property-binding

Angular 9 - Property Binding with undefined


I have a component called CustomTextBox

In my CustomTextBox.ts , written as

@Input('id') _id:string
@Input('class') _class:string

In my CustomTextBox.htm, By Using Property Binding, written as

<textarea [id]="_id" [class]="_class"></textarea>

I can able to call the component as any one of the below option from app component

<CustomTextBox></CustomTextBox>
  <CustomTextBox id="sampleid"></CustomTextBox>
  <CustomTextBox class="sampleid"></CustomTextBox>

id and class are optional

But when Called <CustomTextBox></CustomTextBox> Generating the code as below

<CustomTextBox id="undefined" class="undefined"></CustomTextBox>

how can i make property as optional if the values are null or undefined

Stackbitz Solution

https://stackblitz.com/edit/angular-ivy-v1sybw


Solution

  • Try to write this in your template

    <textarea [attr.id]="_id?_id:null" [attr.class]="_class?_class:null"></textarea>
    

    This will check if your _id and your _class are set, if not the return value will be null, this will have the effect of removing the attribute and so not showing an undefined value.