Angular Elements should be able to emit/dispatch an event while initialization
See original GitHub issue🐞 bug report
Affected Package
The issue is caused by package @angular/elements
Description
We encountered a bug in Angular Elements that the element is not able to emit an event while initializing the component. We tried to emit the event using one of the Angular Component lifecycle hooks (ngOnInit
, ngAfterContentInit
, ngAfterContentChecked
, ngAfterViewInit
). Unfortunately, they were not emitted.
🔬 Minimal Reproduction
Here is a simple component example:
@Component({
selector: 'test-component',
templateUrl: './test-component.component.html',
styleUrls: ['./test-component.component.scss']
})
export class TestComponent implements AfterViewInit {
@Output() public connected: EventEmitter<any> = new EventEmitter<any>();
ngAfterViewInit() {
this.connected.emit();
}
}
Component Usage
const comp = document.createElement('test-component');
comp.addEventListener('connected', function(eventParams) {
console.log('initialized!!!!!'); // will not be called
});
document.body.append(comp);
Live example is available also on stackblitz.com : https://stackblitz.com/edit/angular-issue-repro2-hssxfc
🌍 Your Environment
Angular Version: 6.x & 7.x
Anything else relevant?
I checked the code of the createCustomElement
function and found out that the listening to events and dispatching them is achieved after the component is connected! In other words, the statement here:
https://github.com/angular/angular/blob/699ecac2c28006df807e240e226e7dbaf9012d3d/packages/elements/src/create-custom-element.ts#L167
is called after this.ngElementStrategy.connect(this);
which means that the events will not dispatched as custom events till the ngComponent is initialized.
Moreover, I think it would be great to get a callback/hook when the Web Component is connected to the DOM. Such as componentConnected()
hook.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
@dimarafonseca That should be https://github.com/angular/angular/issues/27771, doesn’t quite relates to this one.
A better explanation can be found at https://github.com/angular/angular/issues/29050#issuecomment-468786510.
This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.