Search code examples
javascriptvue.jsvuejs2vue-componentv-for

How to add a font awesome icon dynamically in Vue.js


I have two inputs positioned in a modal and a button that generates two more inputs when the user clicks on it. It works but I want to add a font awesome icon next to the two inputs only for the dynamically created inputs, how can I achieve this in Vue? Here is my code so far:

<div class="price-round-creation-containe" v-for="(shareholder, index) in shareholders" :key="index">
  <div>
    <input v-model="shareholder.username" :name="`shareholders[${index}][username]`" type="text" class="form-control input" >
  </div>
  <div>
    <input v-model="shareholder.investment" :name="`shareholders[${index}][investment]`" type="text" class="form-control input" >
  </div>
</div>

<p
  class="add-new-shareholders-p"
  @click="createNewPricedRoundShareholder"
>
  <i class="fa fa-plus-circle fa-lg" />ADD NEW SHAREHOLDER
</p>

my data:

shareholders: [
  {
    investment: "Investment",
    username: "Username"
  },
]

and the function for my add button:

createNewPricedRoundShareholder() {
 this.shareholders.push({
    username: "Username",
    investment: "Investment"
  },
}

Solution

  • You could add an extra property dynamic: true to the additions:

    this.shareholders.push({
      username: "Username",
      investment: "Investment",
      dynamic: true
    })
    

    and check for it when showing the inputs:

    <div>
       <input v-model="shareholder.username" :name="`shareholders[${index}][username]`" type="text" class="form-control input" >
       <i v-if="shareholder.dynamic" class="fa fa-plus-circle fa-lg" />
    </div>
    <div>
       <input v-model="shareholder.investment" :name="`shareholders[${index}][investment]`" type="text" class="form-control input" >
       <i v-if="shareholder.dynamic" class="fa fa-plus-circle fa-lg" />
    </div>