【发布时间】:2020-05-02 05:06:27
【问题描述】:
我是 Angular 的新手。 This 问题与我的问题非常相似,但没有回答我的问题。就我而言,这两个组件是独立的,这意味着它们不是彼此的父子。它们是分开的并且在同一目录级别。这就是为什么我的问题与其他问题不同的原因。我尝试使用:
- @ViewChild();
- @Output() ....EventEmitter()
但我仍然收到navbar.component.ts 的错误:
ERROR TypeError: "this.articles is undefined"
我的第一个组件是NavBar,我的第二个组件是Articles
所以场景是,NavBar 的pressed() 方法必须调用Articles 的callSearch(arg) 方法。
这是我的 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>
这是我想从 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>
请纠正我。
PS:这里是stackblitz。
【问题讨论】:
-
能把组件的html包含进去吗?
-
这是answer你的问题吗
-
“这两个组件是独立的,这意味着它们不是彼此的父子” - 那么
@ViewChild不可能工作。您可能希望通过它们的公共父组件(如果它们属于公共父组件)或服务进行通信。 -
好的。我将在此处包含 HTML。事实上,我正在尝试创建 stackblitz。我认为这对每个人来说都会更容易。
-
这里是stackblitz
标签: javascript angular typescript