Angular 2中Button绑定data-item-id报错:未知属性问题求助
Hey there, I’ve run into this exact issue before when integrating Snipcart with Angular—let’s get you sorted out quickly!
Why This Happens
Angular treats any attribute wrapped in square brackets (like [data-item-id]) as a component @Input property. Since native <button> elements don’t have a data-item-id input property, Angular throws that error. Snipcart just needs plain HTML attributes, not Angular’s binding syntax by default.
Solutions Depending on Your Use Case
1. Static Product Values
If your product details are hardcoded (not coming from a component variable), skip the square brackets entirely and write the attributes normally:
<button class="snipcart-add-item" data-item-id="coffee-mug-001" data-item-name="Ceramic Coffee Mug" data-item-price="19.99" data-item-url="/products/coffee-mug" > Add to Cart </button>
2. Dynamic Product Values (From Component)
When you need to bind values from your Angular component (like a product object), use Angular’s attr. prefix to tell it to render this as a native HTML attribute instead of an input property:
<button class="snipcart-add-item" [attr.data-item-id]="selectedProduct.id" [attr.data-item-name]="selectedProduct.name" [attr.data-item-price]="selectedProduct.price" [attr.data-item-url]="selectedProduct.url" > Add to Cart </button>
Quick Check to Ensure Snipcart is Set Up
Don’t forget to confirm you’ve added the Snipcart script and container to your index.html (this is easy to overlook!):
<!-- Add this before the closing </body> tag --> <script src="https://cdn.snipcart.com/themes/v3.0.27/default/snipcart.js"></script> <div hidden id="snipcart" data-api-key="YOUR_SNIPCART_API_KEY"></div>
That should resolve the binding error and get your Snipcart buttons working as expected.
内容的提问来源于stack exchange,提问作者Zain Merchant

