angular学习总结九——父组件与子组件数据的双向绑定

父子组件双向绑定,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的值
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值