假设我有一个具有自动完成功能的下拉控件,如图所示
COMPONENT:
import {Component, ElementRef} from 'angular2/core';
@Component({
selector: 'my-app',
host: {
'(document:click)': 'handleClick($event)',
},
template: `
<div class="container" >
<div class="input-field col s12">
<input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()>
<label for="country">Country</label>
</div>
<div class="suggestions" *ngIf="filteredList.length > 0">
<ul *ngFor="#item of filteredList" >
<li >
<a (click)="select(item)">{{item}}</a>
</li>
</ul>
</div>
</div>
`
})
export class AppComponent {
public query = '';
public countries = ["Albania","Andorra","Belarus","Canada"];
public filteredList = [];
public elementRef;
constructor(myElement: ElementRef) {
this.elementRef = myElement;
}
filter() {
if (this.query !== ""){
this.filteredList = this.countries.filter(function(el){
return (el.toLowerCase().substr(0,this.query.length) === this.query.toLowerCase()) == true;
}.bind(this));
}else{
this.filteredList = [];
}
}
select(item){
this.query = item;
this.filteredList = [];
}
handleClick(event){
var clickedComponent = event.target;
var inside = false;
do {
if (clickedComponent === this.elementRef.nativeElement) {
inside = true;
}
clickedComponent = clickedComponent.parentNode;
} while (clickedComponent);
if(!inside){
this.filteredList = [];
}
}
}
HTML
<body>
<my-app>Loading...</my-app>
如何使此组件可重用,以便我可以在绑定不同内容的表单中使用它。与国家/州/城市一样,或者可能是使用angular2组件创建的注册页面中的非相关数据。
答案 0 :(得分:0)
ControlValueAccessor
以使其与[(ngModel)]="..."
一起使用
例如,请参阅https://github.com/angular/angular/blob/22916bb5d1abf2818d7d8d99d39605af251f42e4/modules/%40angular/forms/src/directives/checkbox_value_accessor.ts @Input() public query = '';
@Input() public countries;
然后你就可以使用你的控件了
<my-comp [query]="abc" [countries]="['Albania','Andorra','Belarus','Canada']"
@Output() queryChange:EventEmitter<String> = new EventEmitter<String>();
能够绑定结果,如
<my-comp [(query)]="valueProp"