簡體   English   中英

Angular 具有 onSelectionChange 事件的可重用墊選擇組件

[英]Angular ReUsable mat-select component with onSelectionChange event

我想制作一個通用的可重用墊選擇組件,因此我可以在我的 Angular 應用程序中的多個組件中使用它。 到目前為止,我已經讓它工作了,但我現在面臨的唯一挑戰是如何使“onSelectionChange($event)”在不同的實現上運行。

可重復使用的選擇組件。html

<mat-form-field>
  <mat-select>
    <mat-option *ngFor="let option of options" [value]="option.value">
      {{ option.text }}
    </mat-option>
  </mat-select>
</mat-form-field>

可重用的選擇組件.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { DropdownOption } from '../../models/DropdownOption';

@Component({
  selector: 'reusable-select',
  templateUrl: './reusable-select-component.html',
  styleUrls: ['./reusable-select-component.scss'],
})
export class ReusableSelectComponent implements OnInit {
  @Input() control: FormControl;
  @Input() options: DropdownOption[];

  constructor() {}

  ngOnInit() {}
}

頁面組件.html

<reusable-select
    [control]="control"
    [options]="dropDownOptions"
    (selectionChange)="onChange($event)"
  ></reusable-select>

頁面組件.ts

@Input() control: FormControl;
@Input() dropDownOptions: DropdownOption[] = [];

public ngOnInit() {
    this.dropDownOptions.push({
      value: 1,
      text: 'Test 1',
    });

    this.dropDownOptions.push({
      value: 2,
      text: 'Test 2',
    });

    this.dropDownOptions.push({
      value: 3,
      text: 'Test 3',
    });
}

我的問題是如何在我實現的頁面中調用 onSelectionChange() ? onSelectionChange 將與一個實現不同,所以我不能在組件本身上定義它,但是 function 應該在實現這個可重用組件的頁面上實現。

還有一些頁面不需要 onSelectionChange,但就像沒有 function 調用的正常下拉菜單一樣。

可重復使用的選擇組件。html

<mat-form-field>
  <mat-select (selectionChange)="onSelectionChange($event)">
    <mat-option *ngFor="let option of options" [value]="option.value">
      {{ option.text }}
    </mat-option>
  </mat-select>
</mat-form-field>

可重用的選擇組件.ts

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { MatSelectChange } from '@angular/material/select';
import { FormControl, Validators } from '@angular/forms';
import { DropdownOption } from '../../models/DropdownOption';

@Component({
  selector: 'reusable-select',
  templateUrl: './reusable-select-component.html',
  styleUrls: ['./reusable-select-component.scss'],
})
export class ReusableSelectComponent implements OnInit {
  @Input() control: FormControl;
  @Input() options: DropdownOption[];
  @Output() selectionChange = new EventEmitter<MatSelectChange>();

  constructor() {}

  ngOnInit() {}

  onSelectionChange(event) {
    this.selectionChange.next(event);
  }
}

頁面組件.ts

  onSelectionChange(event) {
    console.log(event)
  }

頁面組件.html

<reusable-select (selectionChange)="onSelectionChange($event)></reusable-select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM