我有一个名为“Employee-type”的组件(包括一个select组件),它将用于显示相应的员工列表(datagrid) . 如何在表单中重复使用相同的组件,如下所示,具有有效,无效,脏,触摸等额外功能?
我使用@ angular / material mat-select创建了一个简单的可重用选择组件 . 结帐live demo .
我-select.component.ts
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'my-select', template: ` <mat-form-field> <mat-select [formControl]="ctrl" [placeholder]="placeholder"> <mat-option *ngFor="let option of options" [value]="option"> {{ option }} </mat-option> </mat-select> </mat-form-field> `, styles: [`:host { display: block; }`] }) export class MySelectComponent { @Input() ctrl: FormControl; @Input() options: string[]; @Input() placeholder: string; }
用法示例:
app.component.html
<form [formGroup]="form"> <my-select [ctrl]="form.get('cities')" [options]="cities" placeholder="Cities"></my-select> <my-select [ctrl]="form.get('countries')" [options]="countries" placeholder="Countries"></my-select> </form>
app.component.ts
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form: FormGroup; cities = ['Krakow', 'Warszawa', 'Gdansk']; countries = ['Poland', 'Germany', 'Sweden']; constructor(private fb: FormBuilder) { this.form = this.fb.group({ cities: ['', Validators.required], countries: ['', Validators.required], }) } }
1 回答
我使用@ angular / material mat-select创建了一个简单的可重用选择组件 . 结帐live demo .
我-select.component.ts
用法示例:
app.component.html
app.component.ts