'Trigger click event dynamically in angular 8
Tried to trigger click event for element reference based on index but not working in angular 8.If anyone know please help to find solution.
app.component.html:
<div class="st-item" *ngFor="let data of datalist; let i = index">
<input type="radio" name="st" id="{{data.name}}" />
<label for="{{data.name}}" #items (click)="showproduct(data.name)">
<span>
{{data.display}}
</span>
</label>
</div>
app.component.ts:
@ViewChildren('items') liItems: QueryList<ElementRef>
ngOnInit(){
const indexItem = 2;
this.liItems.forEach((item, index) => {
if (index === (indexItem - 1)) (item.nativeElement as HTMLElement).click();
});
}
Solution 1:[1]
If you didn't get any error in the console then I don't know what happened but 2 things I see is wrong there:
ngOnInit
is being called directly after component init but view is not always finished before this call. In this case you should tryngAfterViewInit
orngAfterContentInit
to be surengFor
and whole view is rendered. You didn't say where you calledconsole.log(this.liItems)
but calling it in this case inngOnInit
and getting anything thanundefined
would be weird- In case you get
ExpressionChangedAfterItHasBeenCheckedError
try to encapsulate your code insetTimeout
function
Let me know if there will be any new errors or you didn't get around with. Good luck!
Solution 2:[2]
You can check article related to it, may be you will found solution here.
https://dev.to/gloriamaris/how-to-programmatically-trigger-click-event-in-angular-4--3i6a
Note: I know this very late reply to this question, but may be this is helpful for someone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ThaFog |
Solution 2 | Dinesh Satpute |