简体   繁体   中英

Angular 8/9 How to disable buttons dynamically that were also created dynamically?

So I have a project where I had sets of buttons created dynamically. Each set has two buttons, and when one is clicked it's collapsible content appears. If you click the other button in the set, the first button's content disappears, and the second button's content appears. (For the sake of brevity I figured I'd exclude the content). The total sets can be determined by simply changing the value of a variable called totalSetsOfButtons. Right now, it is set to the number 8, so there will be eight sets of two buttons.

In the first button's collapsible content, there is an image upload that the user can interact with. If the user interacts with this, I want the second button to disable. When the user loads an image, a variable called isImageAdded is switched from null to true , which tells the disabled attribute to trigger in the second button as you can see below. The problem is, if an image is added, this disables ALL of the second buttons in every set.

<div *ngFor="let item of totalSetsOfButtons; let i = index">
  <h5 class="set-num">Set #{{i+1}}</h5>

  <div class="set-btns">
    <div class="set{{i}}-btn1" id="set-btn1">
      <p>
        <button class="btn btn-primary btn-light question-btn1" type="button" data-toggle="collapse" [attr.data-target]="'#collapseExample' + i" aria-expanded="false" [attr.aria-controls]="collapseExample1"> Add New Question
        </button>
      </p>
    </div>

    <div class="set{{i}}-btn2" id="set-btn2">
      <p>
        <button class="btn btn-primary btn-light question{{i}}-btn2" [disabled]="isImageAdded" type="button" data-toggle="collapse" [attr.data-target]="'#collapseExample2' + i" aria-expanded="false"
                        [attr.aria-controls]="collapseExample2">Add Pre-existing Question
        </button>
      </p>
    </div>
  </div>
</div>

How do I only disable the second button in the set the user is interacting with? Any help is appreciated!

The problem is that you have set the [disabled] property to isImageAdded which is a global property in the component. So setting it to true/false will affect the disabled state of all the buttons bound to it.

In it's place, you might prefer to set a variable in the totalSetsOfButtons array, and use that to enable/disable the corresponding button.

For example:

totalSetsOfButtons = [
  { ...yourEarlierArgs, isImageAdded: false },
  { ...yourEarlierArgs, isImageAdded: false },
  ... more 6 similar items
];

And when you interact with the application, you can update the value of the isImageAdded in the array item, and use it.

<button [disabled]="item.isImageAdded">Add Pre-existing Question</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM