2016-08-21 61 views
2

我的組件是一個自動完成器。但它位於一個固定的高度div內,並且結果div需要被父對象放置並正確顯示。在angular2中做到這一點的正確方法是什麼?我如何使用angular2添加元素到身體

@Component({ 
    selector: 'autocomplete', 
    template: ` 
     <div class="container" > 
      <div> 
       <input id="search" type="text" class="validate filter-input" [(ngModel)]=query (keyup)="filter()"> 
      </div> 
      <div *ngIf="filteredList.length > 0"> 
       <ul *ngFor="let item of filteredList" > 
        <li > 
         <a (click)="select(item)">{{item}}</a> 
        </li> 
       </ul> 
      </div> 
     </div>`, 
}) 
export class AutocompleteComponent { 
    private items: string[]; 
    public query: string; 
    public filteredList: string[]; 
    public elementRef: ElementRef; 

    constructor(element: ElementRef) { 
     this.items = ['foo', 'bar', 'baz']; 
     this.filteredList = []; 
     this.query = ''; 
     this.elementRef = element; 
    } 
    filter() { 
     if (this.query !== '') { 
      this.filteredList = this.items.filter(function(item) { 
       return item.toLowerCase().indexOf(this.query.toLowerCase()) > -1; 
      }.bind(this)); 
     } 
     else { 
      this.filteredList = []; 
     } 
    } 
} 
+0

會不使用CSS來獲得所需的結果?相對於輸入的位置? – garethb

+0

@garethb元素處於固定高度,因此任何溢出都會隱藏起來 – Brett

回答

1

我還沒有找到一個方式,一個組件可以添加元素的父級,所以我建議以下(這爲我工作):

你應該將結果div來單獨按照您的建議,以身體爲父母的組件。要從原始組件控制此組件,可以使用ngOnInit和ngOnDestroy生命週期掛鉤將自動完成組件的存在切換到結果div組件。使用單件服務(由您的應用程序模塊提供)來存儲自動完成組件的存在狀態。

+0

謝謝。一位朋友告訴我使用'body'作爲選擇器,並促使我遵循與描述相同的邏輯,將結果作爲單獨的組件使用。 – Brett

0

您可以AutocompleteComponent的構造運動組件的HTML,無論你想

constructor(){ 
document.querySelector('body').appendChild(elementRef.nativeElement); 
      } 

但是你必須在組件中ngOnDestroy即破壞去除組件的HTML()函數

ngOnDestroy(){ 
document.querySelector('body').removeChild(elementRef.nativeElement); 
} 
相關問題