Reputation: 55
I have two pages and widgets. I call page2 in page1 with selector, and my widgets are opening in page2 in the same way.
The problem is, i can call page2's functions in widget. But i can't access page1's properties(they are undefined). I think page1's dying when widgets are opened. Is it normal in Angular structure? Can I provide that page1's still running?
Thank you
in page1 view:
<page2></page2>
in page2 view:
<widget><widget>
And my widget's .ts file.
_page2.Test2() //it's ok
I can access this way. I define _page2 in widget's constructor. But i can't define _page1. It gives 'No provider' error.
_page1.Test1() // this is not possible.
What might this be about? And two pages have NgModule. Page2 doesn't thrown provider error, but page1 did it.
Upvotes: 0
Views: 809
Reputation:
Your code should look like this I assume ?
app.html
<page1></page1>
page1.html
<page2></page2>
page2.html
<widget1></widget1>
<widget2></widget2>
In this case, you have several solutions. First, inject the reference of page 1 into your widgets like so
constructor(
@Inject(forwardRef(() => PageOneComponent)) private page1: PageOneComponent,
) {}
And before anyone tells you not to do it : yes, this is a bad practice because it creates a strong dependency. But this answers the question.
Second option is to create view children and assign their values on the fly :
page1 HTML & TS
<page2 #p2></page2>
@ViewChild(PageTwoComponent) p2: PageTwoComponent;
page2 HTML & TS
<widget1 #w1></widget1>
<widget2 #w2></widget2>
@ViewChild(WidgetOneComponent) w1: WidgetTwoComponent;
@ViewChild(WidgetTwoComponent) w2: WidgetTwoComponent;
Widgets TS
page1: PageOneComponent;
Now, in your first component, you can do
this.p2.w1.page1 = this;
this.p2.w2.page1 = this;
But this is gross and you should not do that.
Third solution, use a service with subjects.
service
export class MyService {
onEvent: Subject<any> = new Subject();
propagate() { this.onEvent.next(null); }
}
widgets
constructor(private service: MyService) {
// you can call
service.propagate();
}
page 1
// Subscribe to the propagation
this.service.onEvent.subscribe(() => { this.myMethod(); });
This should be the way to do it.
Upvotes: 1