问题
I have a series of button created by ngFor which all have custom attributes binded like this:
[attr.queryParam1]="button['something'] | clean"
(click)="next($event)"
Then in the controller:
this.service.lvl1Docs($event.target.attributes["queryParam1"].value).subscribe
But in chrome I'm getting very inconsistent behaviour, the source seems to reveal the attributes are there and are correct but if I click them I get this error in console and nothing happens:
ERROR TypeError: Cannot read property 'value' of undefined
at DocsBuilderComponent.push../src/app/docs-builder
/docs-builder.component.ts.DocsBuilderComponent.reveallvl1
Everything seems to work fine in firefox though and if I keep clicking in chrome it eventually works fine. I had no luck troubleshooting this all week and I can't seem to effectively reproduce from scratch.
My question is, is there a better/different way to bind these two so I can send that iterated attribute as a GET request param?
I should mention I need to use about 5 params for each button slightly later on and can't bind to something like 'value' or 'id', hence trying to use attribute binding.
回答1:
In an *ngFor you have access to all the items that are being looped over. So why add attributes to a button if you just need the data that attribute may or may not contain.
Whatever array you are iterating over, add the query param fields to the objects within the array.
Heres an example
<button *ngFor="let item of items" (click)="next(item.queryParamsOrWhatever)">
{{item.buttonName}}
</button>
Does this answer your question? Or is their some reason you need to add attributes to the button.
来源:https://stackoverflow.com/questions/51560936/angular-6-attribute-binding-bug-possible-workarounds