2017-06-20 40 views
0

我正在開發一個Angular組件custom-select,它在內部使用本地html選擇。 的custom-select模板實現看起來是這樣的:在Angular 2+中使用自定義組件的更改輸出

<!-- custom-select.component.html --> 

<select class="select" [(ngModel)]="selectedId" (change)="onChange()"> 
    <option *ngFor="let question of questions" [value]="question.id">{{ question.text }}</option> 
</select> 

因此,有是內部選擇一個change處理程序。

對於我的自定義選擇組件,我希望有一個名爲change的輸出綁定。 所以對於定製選擇組件對應的TS文件看起來像這樣:

@Component({ 
    selector: 'custom-select', 
    templateUrl: './custom-select.component.html' 
}) 
export class CustomSelectComponent implements OnInit { 
    @Input() options: Array<{ id: string, text: string }>; 
    @Output() change = new EventEmitter<string>(); 

    selectedId = ''; 

    constructor() { } 

    onChange() { 
    this.change.emit(this.selectedId); 
    } 
} 

現在我可以用我的自定義選擇,如:

<custom-select [options]="options" (change)="onChange($event)"></custom-select>` 

如果我這樣做,選擇更改處理被稱爲兩次。看起來第一個電話是我期待的電話。第二個調用似乎是由內部選擇更改處理程序觸發的。

如果我將自定義選擇的處理程序重命名爲selectChange,則一切正常。

<custom-select [options]="options" (selectChange)="onChange($event)"></custom-select> 

但因爲我想有一個乾淨的API,我更喜歡命名輸出change,而不是selectChange

有沒有辦法做到這一點?

回答

0

你可以使用這樣的:

@Output('selectChange') change = new EventEmitter<string>(); 

這是指selectChange。您可以詳細瞭解此here

+0

這就是我目前使用它,並且工作正常。你是對的。但是我想用'@Output('change')change = new EventEmitter ();' ,這樣我就可以在使用組件'' –

+0

你想用什麼? – SaiUnique

相關問題