当用户在输入中输入字母时,我尝试使用 ngOnChanges 创建搜索过滤器。这是我的代码:
export class SearchComponent implements OnInit, OnChanges {
@Input() search:string
// trying to get this to run each time the input value changes
public ngOnChanges(changes: any) {
console.log(changes.search);
}
}
@NgModule({
imports: [MaterialModule, FlexLayoutModule, BrowserModule, FormsModule]
// declarations, providers, exports also defined here
})
组件模板中的输入元素:
// using Material Design Library
<input mdInput [search]="searchText" type="text" placeholder="Search"></input>
或者我可以只使用这样的@Input:
<search-component [search]="searchText"></searchComponent>
但是这里的 searchText 绑定(bind)到我的 Controller 吗?
我不断收到的错误是“无法绑定(bind)到“搜索”,因为它不是“输入”的已知属性。
我知道 @Input 装饰器已经处理了这个问题,但显然我在这里遗漏了一些东西。
注意:我确实使用 (ngModelChange) 添加了过滤器并绑定(bind)到 Controller 中的 [(ngModel)] 值。工作正常。但听起来使用 ngOnChanges 是执行此操作的最佳方法,因此我试图了解如何使其工作。谢谢
最佳答案
@Input()
允许您将表达式绑定(bind)到用它标记的属性,因此将 search
声明为输入属性允许您在该属性上使用属性绑定(bind)。因此,要使用它,只需在您想要放置 SearchComponent
的某个组件模板中执行此操作,例如
<app-root>
<search-component [search]='"dummy text"'></searchComponent>
</app-root>
您无法对 input
元素上的 search
属性进行属性绑定(bind),因为 HTMLInputElement
接口(interface)没有此类成员,因此会出现异常。您只能对要绑定(bind)到的特定元素上存在的属性进行属性绑定(bind)
关于javascript - 在 Angular 2 中使用 @Input Decorator 触发 ngOnChanges 生命周期钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506218/