【问题标题】:Angular 5 pass ngModel through componentsAngular 5 通过组件传递 ngModel
【发布时间】:2022-01-18 17:29:08
【问题描述】:

我创建了一个简单的组件,它包装了 bootstrap 的 typeahead 控制器,因此可以按照我对应用程序的要求进行配置。该组件有一个公共变量selectedWorker,即来自预输入的ngModel

所以现在,当我在其他地方使用这个组件时,我想做这样的事情:

<app-worker-lookup [(ngModel)]="foo"></app-worker-lookup>

然后将调用者的foo 变量绑定到具有选定值的查找组件的公共变量。我不确定如何实现。

【问题讨论】:

标签: angular angular5 angular-ngmodel


【解决方案1】:

为了可以在您的组件中使用 ngModel,您的类必须实现 ControlValueAccesor 并将组件添加到提供令牌

组件

    @Component({
    selector: 'component',
    templateUrl: '../component.html',
    styleUrls: ['../component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => Component),
            multi: true
        }
    ]
}) 
export class Component implements ControlValueAccessor {

        //
        // Now add ngModel property binding
        @Input() ngModel : NgModel;

        ....

        //
        // ControlValueAccessor implementation
        writeValue(value:any) {
           this.value = value;
        }

        registerOnChange(fn) {
            this.propagateChange = fn;
        }

        registerOnTouched(fn){
        }

        private propagateChange = (_:any) => {};
    }

【讨论】:

  • 嗨..我明白了,没有 DecoratorFactory 的提供者,你知道为什么吗?
  • 尝试重新安装node_modules,你不一定有问题。或者留下来确保你的代码写得很好。
  • 如果你得到“装饰工厂没有提供者”,你应该在提供者的 useExisting 属性中用你的组件名称替换 Component。
【解决方案2】:

为了在组件上使用ngModel,您需要将该组件实现为自定义表单控件。这应该相对简单,因为您的组件的表单行为将与预先输入的相同。

Here's a nice article on how to do this,或Stack Overflow answer,如果您愿意的话。

需要注意的是,为了正确实现双向绑定,您需要将 typeahead 组件的 [(ngModel)] 属性拆分为 [ngModel]="selectedWorker" (ngModelChange)="onChange($event)",以便您可以在 onChange 中调用 writeValue()方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-18
    • 2019-01-09
    • 2018-09-25
    • 2021-02-09
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多