2017-06-20 6 views
0

内部的にhtml selectを使用するAngularコンポーネントcustom-selectを開発しています。 custom-selectの テンプレートの実装は次のようになります。角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>` 

二度。最初のコールは私が期待していたコールだと思われます。 2番目の呼び出しは、内部選択変更ハンドラによって起動されたようです。

カスタムセレクトのハンドラの名前をselectChangeに変更しても、すべて正常に動作します。

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

しかし、私はクリーンなAPIを持っていると思いますので、私が代わりにselectChangeの出力changeに名前を付けることを好みます。

これを行う方法はありますか?

答えて

0

あなたはこのように使用することができます:selectChangeを指し

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

を。することができますより多くの彼らの公式ドキュメントではいくつかのことより、この上でこのhere

+0

。あなたが正しいです。しかし、私はコンポーネント '();' change)= "onChange($ event)"> ' –

+0

あなたは何を使いたいですか? – SaiUnique

関連する問題