当我尝试将值从父组件传递给子组件时出现错误,基本上是试图在搜索框中获取用户的输入并将其传递给搜索组件以显示从API接收到的数据到卡。建议可行的解决方案或替代方案也可以采用这种方法。 到目前为止,我尝试过的步骤: 将@Input从SearchText重命名为text,App.module的NgModule声明中包含SearchComponent,但仍然遇到错误。
app.component.html
<mat-toolbar color="primary">
<span>The Deccan Chronical</span> <span class="spacer"></span>
<div>
<input class="form-control" type="text" placeholder="Search" name="searchValued" aria-label="Search" [(ngModel)]= "text">
<button >Submit</button>
<app-search [text] = "text"></app-search>
<button mat-button [routerLink]="['/']">Home</button>
<button mat-button [routerLink]="['/headlines']">Headlines</button>
<button mat-button [routerLink]="['/sources']">Sources</button>
<button mat-button [routerLink]="['/favorites']">Favorites</button>
</div>
</mat-toolbar>
<div class="container"><router-outlet></router-outlet></div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';
import { MatToolbarModule } from '@angular/material/toolbar';
import { HomeComponent } from './home/home.component';
import { HttpClientModule } from '@angular/common/http';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import {SearchComponent} from './search/search.component';
@NgModule({
declarations: [AppComponent, HomeComponent,SearchComponent],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
MatToolbarModule,
HttpClientModule,
Ng2SearchPipeModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
search.component.ts
import { Component, OnInit,Input } from '@angular/core';
import { NewsService } from 'src/app/services/news.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
@Input() text : string;
news;
newsSubscription;
length;
pageSize = 8;
page = 1;
constructor(private newsapi:NewsService){
console.log('app component constructor called');
}
ngOnInit() {
this.getData();
}
getData() {
this.newsSubscription = this.newsapi
.getData(
`top-headlines?country=us&pageSize=${this.pageSize}&page=${this.page}`
)
.subscribe(data => {
this.news = data;
this.length = data['totalResults'];
});
}
getSearchData(text) {
this.newsapi
.getData(`everything?q=${text.toLowerCase()}`)
.subscribe(data => {
this.news = data;
});
}
}