将可重用组件绑定到不同的内容

时间:2016-06-22 03:39:09

标签: angular angular2-forms

假设我有一个具有自动完成功能的下拉控件,如图所示

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组件创建的注册页面中的非相关数据。

1 个答案:

答案 0 :(得分:0)

@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"