angular自定义表单组件支持 formControlName

Fork Me On Github

默认的 ngModel 的实现方式为

ts
                 
@Component({
  selector: 'app-switch',
  template: `
    <div (click)="tapAdd()">{{ value }}</div>
  `,
  styleUrls: ['./switch.component.scss'],
})
export class SwitchComponent { 

    @Input() value = 0;
    @Output() valueChange: EventEmitter<number> = new EventEmitter();

    public tapAdd() {
        this.valueChange.emit(++ this.value);
    }
}
1234567891011121314151617

使用

html
 
<app-switch [(ngModel)]="value"></app-switch>
1

但这种方式是不支持 formControlName 绑定的

会提示No value accessor for form control with name: 错误

修改代码

因此必须换种方式

ts
                                           
@Component({
    selector: 'app-switch',
    template: `
        <div (click)="tapAdd()">{{ value }}</div>
    `,
    styleUrls: ['./switch.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => SwitchComponent),
            multi: true
        }
    ]
})
export class SwitchComponent implements ControlValueAccessor { 

    public value = 0;
    public disable = false;

    onChange: any = () => { };
    onTouch: any = () => { };

    public tapAdd() {
        if (this.disable) {
            return;
        }
        this.onChange(++ this.value);
    }

    writeValue(obj: any): void {
        this.value = obj;
    }
    registerOnChange(fn: any): void {
        this.onChange = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouch = fn;
    }
    setDisabledState?(isDisabled: boolean): void {
        this.disable = isDisabled;
    }
}
12345678910111213141516171819202122232425262728293031323334353637383940414243

现在可以就支持两种方式了

html
   
<app-switch [(ngModel)]="value"></app-switch>

<app-switch formControlName="value"></app-switch>
123

例子

Example with Input

Example with Lazy Loaded Input

Example with Button

点击查看全文
标签: angular
0 1285 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式