I have been using Angular 6 and I am new to the Angular environment too.
My problem is that I have been thinking about this in a jQuery way.
I want to trigger an anchor link on page load like the below jQuery code in Angular 6.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#hello').click(function () {
console.log('yo yo yo .....you good to go.!!!');
});
$('a').trigger('click');
});
</script>
<a id="hello" href="http://www.google.com">Click me</a>
How to achieve this in Angular 6? I know that we can add a click on the elements. But in my project, I don't know have a control on anchor tag. I mean I cannot add click method, instead I want to trigger it externally like jQuery.
You can use renderer2 service dispatchEvent method to dispatch Event
@ViewChild('elem') elem: ElementRef;
constructor(private renderer2: Renderer2) {}
ngOnInit() {
this.renderer2.listen(this.elem.nativeElement, 'click', () => {
alert(111);
});
let event: Event = new Event('click');
this.elem.nativeElement.dispatchEvent(event);
}
Example:https://stackblitz.com/edit/angular-renderer2-dispatch-event-2uhpay