2017-09-05 41 views
0

我寫了一個自定義窗體控件,實現了ControlValueAccessor接口。爲什麼ngModel寫入值兩次

@Component({ 
    selector: 'counter', 
    template: ` 
    <button (click)="increase($event)">+</button> 
    {{counter}} 
    <button (click)="decrease($event)">-</button> 
    `, 
    providers: [{ 
    provide: NG_VALUE_ACCESSOR, 
    useExisting: forwardRef(() => CounterComponent), 
    multi: true 
    }] 
}) 
export class CounterComponent implements OnInit, ControlValueAccessor { 
    private counter: number = 0; 
    private onChange: (_: any) => void; 
    private onTouched:() => void; 

    ngOnInit() { } 

    writeValue(value) { 
    console.log('Write value', value); 
    this.counter = value; 
    } 

    registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } 

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

    increase() { 
    this.counter++; 
    this.onChange(this.counter); 
    } 
    decrease() { 
    this.counter--; 
    this.onChange(this.counter); 
    } 
} 

但是我發現writeValue會觸發兩次,當我使用ngModel

@Component({ 
    selector: 'my-app', 
    template: '<counter [(ngModel)]="count"></counter>', 
    styleUrls: [ './app.component.css' ] 
}) 
export class AppComponent { 
    count = 5; 
} 

output:

Write value null 
Write value 5 

在線例子鏈接:https://stackblitz.com/edit/angular-ngmodel-write-value

+0

你能解釋一下如何writeValue被觸發? –

+0

@RahulSingh我不知道這件事。我想它會在ngmodel改變時觸發。你可以給一些解釋或關於這個的帖子鏈接嗎? – t1mer

+0

我不知道這種方法jsut想檢查它是如何觸發,以便給出任何答案 –

回答