有这个组件:
export class SearchPageComponent implements OnInit {
results: Array<ResultsModel> = [];
public constructor(private searchService: SearchPageService) { }
public ngOnInit(): void {
this.onSearch(new SearchCriteria());
}
public async onSearch($event: SearchCriteria): Promise<void> {
this.results = await this.searchService.searchAsync($event);
}
}
它的模板:
<div class="container-fluid">
<results-list [itemsList.entries]="results"></results-list>
</div>
子组件:
export class ResultsListComponent implements OnInit {
public itemsList: ItemsList<ResultsModel> = new ItemsList<ResultsModel>();
public ngOnInit() {
this.itemsList.init();
}
}
ItemsList
班级:
export class ItemsList<T> {
private resultsObserver = new BehaviorSubject<Array<T>>([]);
@Input() public entries: T[] = [];
public set items(value) { this.resultsObserver.next(value); };
public init() {
this.resultsObserver.subscribe(this.onResults.bind(this));
}
private onResults(entries: T[]): void {
this.isLoading = false;
entries.forEach(entry => this.entries.push(entry));
}
}
我想知道如何将数据传递给ItemsList.entries
属性。我宁愿在模板中保留类似[itemsList.entries]
语法的内容,但它是否可能?
使用上面的代码给我:
Can't bind to 'itemsList.entries' since it isn't a known property of 'results-list'.
我正在努力实现[style.color]="whatever"
正在做的事情。这适用于ng2我认为,为什么我的代码不起作用?
答案 0 :(得分:0)
我相对确定@Input属性仅适用于子组件,而不适用于类型。所以你需要这个:
export class ResultsListComponent implements OnInit {
@Input() itemsList: ItemsList<ResultsModel> = new ItemsList<ResultsModel>();
//...
}
是的,然后你需要绑定到itemsList而不是itemsList.entires:
<div class="container-fluid">
<results-list [itemsList]="results"></results-list>
</div>
但你可能会这样做:
export class ResultsListComponent implements OnInit {
public itemsList: ItemsList<ResultsModel> = new ItemsList<ResultsModel>();
@Input() public entries: T[];
//...
ngOnChanges(): void {
this.itemsList = new ItemsList<ResultsModel>();
this.itemsList.entries = entries;
}
}