angular 实现 自定义类似ngModel的双向绑定

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30101131/article/details/88624213

前言

在angular中[(ngModel)]等价于[ngModel]&(ngModelChange),所以自定义的双向绑定实现同样的两个功能即可

代码

two-way.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-two-way',
  templateUrl: './two-way.component.html',
  styleUrls: ['./two-way.component.css']
})
export class TwoWayComponent implements OnInit {
  value: number = -1;
  @Input('count') get count() {
    return this.value;
  }
  set count (value) {
    this.value = value;
    this.countChange.emit(value);
  }
  @Output() countChange = new EventEmitter();
  constructor() { }

  ngOnInit() {
  }
  addvalue() {
    this.count++;
  }
}

two-way.component.html

<div>
  innner: {{value}}
  <button (click)="addvalue()">inner add</button>
</div>

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';
  myvalue = 1;
  deMyvalue() {
    this.myvalue--;
  }
}

app.component.html

<div>
  myvalue: {{myvalue}} 
  <button (click)="deMyvalue()">de myvalue</button>
</div>
<div>
  <app-two-way [(count)]="myvalue"></app-two-way>
</div>

猜你喜欢

转载自blog.csdn.net/qq_30101131/article/details/88624213
今日推荐