自定义表单控件组件
Custom form control component
我正在努力学习Angular。我尝试做自定义表单控件,里面有 mat-select
,我想用表单提交的值是所选项目。
在阅读了一大堆教程和文档之后,我设法得到了这样的东西:
stripped example of the problem on StackBlitz.
为什么不起作用?
你把事情复杂化了。对于这种简单的情况,您不需要实施 ControlValueAccessor
。您可以使用简单的 @Input()
.
将 FormControl
中继到子组件
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>
我正在努力学习Angular。我尝试做自定义表单控件,里面有 mat-select
,我想用表单提交的值是所选项目。
在阅读了一大堆教程和文档之后,我设法得到了这样的东西: stripped example of the problem on StackBlitz.
为什么不起作用?
你把事情复杂化了。对于这种简单的情况,您不需要实施 ControlValueAccessor
。您可以使用简单的 @Input()
.
FormControl
中继到子组件
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>