在 Angular 2+ 中使用自定义组件的更改输出

Pas*_*rus 6 angular

我正在开发一个custom-select内部使用本机 html 选择的 Angular 组件。的模板实现custom-select如下所示:

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

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

所以有一个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);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我可以使用我的自定义选择,例如:

<custom-select [options]="options" (change)="onChange($event)"></custom-select>`
Run Code Online (Sandbox Code Playgroud)

如果我这样做,选择更改处理程序将被调用两次。看来第一个电话就是我期待的电话。第二个调用似乎是由内部选择更改处理程序触发的。

如果我将 custom-select 的处理程序重命名为selectChange,一切都会正常工作。

<custom-select [options]="options" (selectChange)="onChange($event)"></custom-select>
Run Code Online (Sandbox Code Playgroud)

但由于我想要一个干净的 API,所以我更喜欢命名输出change而不是selectChange.

有什么办法可以做到这一点吗?

Sai*_*que 0

你可以这样使用:

@Output('selectChange') change = new EventEmitter<string>();
Run Code Online (Sandbox Code Playgroud)

其中指的是 selectChange。您可以在这里了解更多相关信息

  • 这就是我目前使用它的方式,效果很好。你是对的。但我想使用 `@Output('change') change = new EventEmitter&lt;string&gt;();` ,以便在使用组件 `&lt;custom-select [options]="options" 时可以使用 `change` 作为属性(change)="onChange($event)"&gt;&lt;/自定义选择&gt;` (2认同)