How do I properly get a reference to the host directive in a ControlValueAccessor?

风格不统一 提交于 2019-12-07 20:32:34
Leon Adler

The comment by Günter Zöchbauer pointed me into the right direction.

To bind a value on a component with ngModel, the component itself needs to implement the ControlValueAccessor interface and provide a forwardRef to itself in the providers: key of the component configuration:

const CUSTOMER_VALUE_ACCESSOR: Provider = CONST_EXPR(
    new Provider(NG_VALUE_ACCESSOR, {
        useExisting: forwardRef(() => CustomerEditor),
        multi: true
    })
);

@Component({
    selector: 'customer-editor',
    template: `template for our customer editor`,
    providers: [CUSTOMER_VALUE_ACCESSOR]
})
class CustomerEditor implements ControlValueAccessor {
    customer: Customer;
    onChange: Function = () => {};
    onTouched: Function = () => {};

    writeValue(customer: Customer): void {
        this.customer = customer;
    }

    registerOnChange(fn: Function): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: Function): void {
        this.onTouched = fn;
    }
}

Usage from a parent component:

@Component({
    selector: 'customer-list',
    template: `
        <h2>Customers:</h2>
        <p *ngFor="#c of customers">
            <a (click)="editedCustomer = c">Edit {{c.name}}</a>
        </p>
        <hr>
        <customer-editor *ngIf="editedCustomer" [(ngModel)]="editedCustomer">
        </customer-editor>`,
    directives: [CustomerEditor]
})
export class CustomerList {
    private customers: Customer[];
    private editedCustomer: Customer = 0;

    constructor(testData: TestDataProvider) {
         this.customers = testData.getCustomers();
    }
}

Every example for ControlValueAccessor always show how to use it with a separate class or a directive on a host component, never implemented on the host component class itself.

In your sample, it seems that your CustomerValueAccessor directive is attached on the CustomerComponent component (the one is the selector customer-editor) and not one of type CustomerEditor. I think that it's the reason why you can't inject it.

What does CustomEditor correspond to?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!