I'm still learning Angular. This question on Stack Overflow is similar to what I'm facing, but it doesn't provide the answer I need. In my case, the two components are independent and not parent-child. They exist at the same directory level, which sets my problem apart from others. I've tried using:
- @ViewChild();
- @Output() ....EventEmitter()
However, I keep encountering an error in navbar.component.ts
:
ERROR TypeError: "this.articles is undefined"
The first component is called NavBar
and the second component is called Articles
So, the challenge is for the pressed()
method in NavBar
to call the callSearch(arg)
method in Articles
.
Below is a snippet of my navbar.component.ts
import { ..., ViewChild } from '@angular/core';
import { ArticlesComponent } from '../articles/articles.component';
@Component({
...
})
export class NavbarComponent implements OnInit {
text='something';
@ViewChild(ArticlesComponent, {static: false}) articles: ArticlesComponent;
constructor() { }
/* This method is triggered by a click event in the HTML page*/
pressed(text: string) {
this.articles.callSearch(text);
}
ngOnInit() {
}
}
navbar.component.html
<li class="nav-item">
<button class="btn" (click)="pressed(text)">Search</button>
</li>
And here is the component I want to call a method from NavBar.
articles.component.ts
import { ... } from '@angular/core';
@Component({
...
})
export class ArticlesComponent implements OnInit {
articles = [];
filteredArticles=[];
constructor(...) { }
ngOnInit() {
...
}
/* invoked from navbar typescript file to trigger SearchFunction below*/
callSearch(text: string) {
this.SearchFunction(text);
}
SearchFunction(text: string) {
this.filteredArticles=(this.articles.filter(e => {
/* some logic*/
}));
}
}
articles.component.html
<div *ngFor="let article of filteredArticles; let i = index;">
<div class="card text-center">
<div class="card-body">
<!-- card design related html -->
</div>
</div>
</div>
If you spot any errors, please point them out.
P.S.: You can access the code on StackBlitz.