自定义表单控件组件

时间:2018-04-05 13:51:33

标签: angular typescript angular-forms

我正在努力学习Angular。我试图在内部设置mat-select的自定义表单控件,并且我想要使用表单提交的值是所选项目。

在阅读了大量的教程和文档后,我设法得到了这样的东西: stripped example of the problem on StackBlitz

为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

你的事情过于复杂。对于这样一个简单的案例,您不需要实现ControlValueAccessor。您可以使用简单的FormControl@Input()转发给子组件。

select.component.ts

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

@Component({
  selector: 'selector',
  templateUrl: './selector.component.html',
  providers: [ ]
})

export class SelectorComponent implements  OnInit {
  @Input() ctrl: FormControl;
  @Input() options: string[];

  ngOnInit() {  }
}

select.component.html

<mat-form-field>
    <mat-select [formControl]="ctrl" placeholder="My select">
        <mat-option *ngFor="let option of options" [value]="option">
            {{ option }}
        </mat-option>
    </mat-select>
</mat-form-field>

Live demo

相关问题