父子组件双向绑定,input输入框值变化检测
实现效果子组件值变化时父组件也变化
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
username = 'zengwe';
}
app.component.html
<h1>test</h1>
<div>
<label for="username">heheda:</label>
<input type="text" [(ngModel)]="username">
</div>
<app-test [(ngModel)]="username" ></app-test>
test.component.html
<div class="toggle-button-container">
<a href="javascript:;" (click)="toggle()" class="text-close">+</a>
<input type="text" [ngModel]="model" (ngModelChange)="modelChange($event)">
</div>
test.component.ts
import { Component, OnInit, Input, forwardRef, AfterViewInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TestComponent),
multi: true
}]
})
export class TestComponent implements OnInit, ControlValueAccessor {
private model: any;
constructor() { }
ngOnInit() {
}
public onModelChange: Function = () => { };
public onModelTouched: Function = () => { };
writeValue(value: any) {
console.log('writeValue');
this.model = value;
}
registerOnChange(fn: Function): void {
console.log('registerOnChange');
this.onModelChange = fn; }
registerOnTouched(fn: Function): void {
console.log('registerOnTouched');
this.onModelTouched = fn;
}
modelChange(value) {
this.model = value;
this.onModelChange(this.model); // 主要是要调用这个去重置绑定的model的值
}
}