0

I am trying to build a shopping web app as a project for my master degree.

So my problem is that when I click the button to add a category(calling the function addCategory in my .ts file) I don't know how to create a div and add it to the html file with the id of the category's name, from the .ts file.

Any help it's welcomed.

<div class="container">
    <div class="row">
        <div class="col-6">
            <h1>Products</h1>
            <button (click)="addCategory()">Add category</button>
            <div id="Products">
            </div>
        </div>
        <div class="col-6">
            <h1>Shopping basket</h1>
            <div id="Shoppingbasket">
                <table id="Productstable" class="table table-bordered">
                    <thead>
                        <tr>
                            <th scope="col">Image</th>
                            <th scope="col">Name</th>
                            <th scope="col">Price</th>
                            <th scope="col">Units</th>
                            <th scope="col">Description</th>
                        </tr>
                    </thead>
                    <tbody id="Productstablebody">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
1
  • 1
    In Angular you not add elements to the .html. In Angular you has "variables" and create the html using these "variables" (in your case you need an array and the array can be an array of strings or an array of object) and *ngFor:angular.io/guide/…. So you only need add elements to your array or change the variable Commented Jun 3, 2021 at 11:25

2 Answers 2

1

I'd suggest looking at the Tour of Heroes tutorial on the Angular web site to learn more.

You can create a list in your component, call it categories, then add more categories when you click the addCategory button. In your html template, you can loop through the categories and create an element for each of them.

I created a minimal example in a Stackblitz. Below is a rough example of how it can be done

Angular component

categories: string[] = [];

addCategory() {
  this.categories.push('category');
}

HTML template

<div *ngFor="let category of categories">
  {{category}}
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

make an array of category; when you click add category add to the array then loop it in html like these

<div *ngFor="let category of categories" [id]="category.name">
</div>

Comments

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.