如何在其他组件中传递{(ngModel)}以在* ngFor中使用? 我有一个导航栏,其中包含要搜索的输入和使用ng2-search-filter的即时消息,我需要在其他组件(带有结果的表)中传递{(ngModel)},但我不能。
app.component.html
<div [@routeAnimations]="o.isActivated ? o.activatedRoute : ''" class="main-content">
<app-navbar></app-navbar>
<router-outlet #o="outlet"></router-outlet>
</div>
navbar.component.html
<input class="form-control" placeholder="Sarch" type="text" name="filter" [(ngModel)]="stringToLook">
table.component.html
<tr *ngFor="let object of (objects$ | async) | filter:filter | paginate: config | orderBy: key : reverse">
filter:stringToLook不起作用(stringToLook未定义)。
table.component.ts
.....
@Input() stringToLook: any;
.....
我阅读了文档并做到了,但是没有用。
html
<form (submit)="setText(filter.value)" >
<input class="form-control" name="filter" placeholder="Cerca" type="text" #filter>
<button type="submit" style="display:none">hidden submit</button>
</form>
ts
filter: string;
setText(filter: string) {
this.filter = filter;
console.log(this.filter);
}
ts
@Input('filter') filter: string;
非常感谢
答案 0 :(得分:0)
我使用服务进行了固定,在服务中我创建了变量String和Setter,在父组件中设置了值,在子组件中获得了值。
filter: string;
setText(filter: string) {
this.filter = filter;
console.log(this.filter);
}
Html
<form (submit)="service.setText(filter.value)" >
<input class="form-control" name="filter" placeholder="Cerca" type="text" #filter>
<button type="submit" style="display:none">hidden submit</button>
</form>
TS
构造函数(...,私有服务:Service)
仅在需要时使用service.filter
答案 1 :(得分:0)
通常,当我们要在组件之间共享数据时,服务是最佳选择。
我建议您使用一种更加异步的方式,使用rxjs可观察对象和主题从服务中获取和设置数据。
更多信息:angular-8-communication-between-components-using-subject-and-observable
服务
_filter = new BehaviorSubject<string>('');
filter$ = this._filter.asObservable();
组件
ngOnInit() {
this.subscription = this.service.filter$.subscribe(x => this.filter = x);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
onChangeFilter(filterNewValue: any) {
this.service._filter.next(filterNewValue)
}