I'm new to Angular. This question is very much similar to mine but doesn't answers my question. In my case, the two components are stand-alone, that means they ain't parent-child to each other. They're separate and at same directory level. That's why my problem is different from the rest. I tried using:
- @ViewChild();
- @Output() ....EventEmitter()
But I'm still getting an error in navbar.component.ts:
ERROR TypeError: "this.articles is undefined"
My first component is NavBar and my second component is Articles
So the scenarioa is, pressed() method of NavBar have to call callSearch(arg) method of Articles.
Here is 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 called on click event from 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 whose method I want to call from NavBar.
articles.component.ts
import { ... } from '@angular/core';
@Component({
...
})
export class ArticlesComponent implements OnInit {
articles = [];
filteredArticles=[];
constructor(...) { }
ngOnInit() {
...
}
/* this is called from navbar typescript and it will call 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>
Please correct me.
PS: Here is the stackblitz.
@ViewChildcan't possibly work. You might want to communicate through their common parent component (if they belong to common parent component), or a service.