Reputation: 591
I have created a web component (let's name it test component) with Angular 8 that receives an input and shows it to the browser (test.component.html
file)
<h3>{{title}}</h3>
The test.component.ts
file receives the input and also logs it in the console
export class TestComponent implements OnInit {
@input() title;
constructor() {}
ngOnInit() {console.log(this.title)}
}
The index.html
of a standalone application that uses the web component looks like this:
<test-component title="this is a string"></test-component>
It correctly displays the string and logs it to the console.
The problem arises when I use the web component inside an existing angular application. The variable I want to pass to the web component is dynamic and comes from the existing application's component. I have tried passing it inside a component that already exists (for example existing-application.component.html
) in two different ways:
<test-component [title]="titleVariable"></test-component>
<test-component title={{titleVariable}}></test-component>
where the titleVariable is defined in the associated existing-application.component.html
file like this
export class ExistingApplicationComponent implements OnInit {
titleVariable= 'this is a string';
constructor() {}
ngOnInit() {}
}
Here, while the h1 html element correctly displays the string the console.log is undefined.
I have also tried logging it (in the web component) in the ngAfterViewInit() instead of the ngOnInit() without any luck.
Does anyone have an idea on why this could be happening? Thanks in advance for your time
Upvotes: 0
Views: 438
Reputation: 1640
The problem is with life-cycle hooks. You need ngOnChanges()
life-cylce hook when you want to access the input()
properties.
NgOnChanges: "Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values. Called before ngOnInit() and whenever one or more data-bound input properties change. "
Upvotes: 2