2017-09-05 43 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想检查它是如何触发,以便给出任何答案 –

回答