writeValue功能agular 2定制组件

问题描述:

调用一次有一个自定义angular2部件象下面这样:writeValue功能agular 2定制组件

模板

<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 binding2-way binding ..这组件获得初始值,但根据输入不改变在all..when我调试它在浏览器中的变化writeValue功能只是在装货被解雇,之后没有得到所有被解雇。

我想你应该叫propagateChange方法,当你选择新的价值

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

Plunker Example

所以每当你想从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

+0

我做了你说的,但仍然无法正常工作..实际上writeValue'必须在'value'发生任何变化后调用,之后'propagateChange'被调用'writeValue'..problem是第一个'writeValue'必须被调用,但它不是在'plunker'例子类型的东西在 – Parid0kht

+0

及部件,你会看到新的值不会冲击片雷管 – Parid0kht

+0

新的价值选择后会出现 – yurzui