繁体   English   中英

ControlValueAccessor类中的writeValue函数在angular 2自定义组件中调用一次

[英]writeValue function in ControlValueAccessor class called once in angular 2 custom component

有一个自定义angular2组件,如下所示:

模板

<input class="form-control" id="searchbox" placeholder="شهر" (keyup)="search()" [(ngModel)]="name" autocomplete="off"/>
<div id="searchresult" *ngFor="let city of cities" (click)="cityselected(city)">
    {{city.name}}
</div>

零件

        @Component({
        moduleId: module.id,
        selector: 'city-search',
        templateUrl: './city-search.component.html',
        styleUrls: ['./city-search.component.css'],
        providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => CitySearchComponent),
                multi: true
            }
        ]
    })
    export class CitySearchComponent implements OnInit, ControlValueAccessor{

        cities: Array<City>;
        name: string;
        displaysearchbox: boolean;

        errorMessage: string;

        constructor(private cityService: CityService 
, private helper : Helper) { }

        ngOnInit() {
            this.cities = new Array<City>();
            this.displaysearchbox = false;
        }

        search(): void {
            if (this.name) {              
 this.cityService.
search(this.helper.arabictopersian(this.name))
.subscribe(
                    data => {
                        this.cities = data as Array<City>
                    }
                    , error => this.errorMessage = <any>error);
            }       
        }

        cityselected(city: City): void {
            this.name = city.name;
        }
        writeValue(value: any) {   //just fire once to get the inital value    
            if (value !== undefined) {
                this.name = value; 
            }
            this.propagateChange(this.name);
        }
        propagateChange = (_: any) => { };

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

因为它在代码组件类中显示实现ControlValueAccessor ,这是我如何使用它:

<form class="form-horizontal">
    <city-search id="bc" name="city" [(ngModel)]="city"></city-search>
    city:{{city}}<!--nothing happens -->
</form>

但是自定义组件具有1-way binding而不是2-way binding ..此组件获取初始值但根本不会根据输入更改进行更改..当我在浏览器上调试它时, writeValue函数在加载时被触发,之后根本没被解雇。

我想你应该在选择新值时调用propagateChange方法

cityselected(city: any): void {
  this.name = city.name;
  this.propagateChange(this.name); 
}

Plunker示例

因此,每当您想要从ControlValueAccessor更新ngControl的值时,您应该调用您在registerOnChange方法中设置的函数

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

通常这种方法称为onChange函数https://github.com/angular/angular/blob/4.2.0-rc.1/packages/forms/src/directives/default_value_accessor.ts#L79

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM