angular4自定义组件非input元素实现ngModel双向数据绑定
发布时间:2020-12-17 10:37:13 所属栏目:安全 来源:网络整理
导读:import { Component,forwardRef } from '@angular/core' '@angular/forms' @Component({ selector: 'app-child'span style="color: #000000",templateUrl: './child.component.html'span style="color: #000000",styleUrls: [ './child.component.css'span s
import { Component,forwardRef } from '@angular/core''@angular/forms'@Component({
selector: 'app-child'<span style="color: #000000">,templateUrl: './child.component.html'<span style="color: #000000">,styleUrls: ['./child.component.css'<span style="color: #000000">],providers: [{ provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() =><span style="color: #000000"> ChildComponent),multi: <span style="color: #0000ff">true<span style="color: #000000"> }] }) export class ChildComponent implements ControlValueAccessor { constructor() { } _data: any; add () { <span style="color: #0000ff">this.childData ++<span style="color: #000000">; } change = (value: any) => {}; <span style="color: #008000">//<span style="color: #008000"> 先定义一个方法,很重要,用于接收registerOnChange()方法里传递回来的方法,然后通过这个方法就能通知到外部组件数据更新。 set childData(value: number) { <span style="color: #008000">//<span style="color: #008000"> childData被更改走该方法 <span style="color: #0000ff">this._data =<span style="color: #000000"> value; <span style="color: #0000ff">this.change(<span style="color: #0000ff">this._data); <span style="color: #008000">//<span style="color: #008000"> 将更新后的数据通知到外部组件 <span style="color: #000000"> } get childData() { <span style="color: #008000">//<span style="color: #008000"> 页面或者方法里面有调用childData就会走该方法 <span style="color: #0000ff">return <span style="color: #0000ff">this<span style="color: #000000">._data; } writeValue(val): <span style="color: #0000ff">void { <span style="color: #008000">//<span style="color: #008000"> 初始化时,获取并监听父组件通过ngModel传递进来的数据 <span style="color: #0000ff">if<span style="color: #000000"> (val) { <span style="color: #0000ff">this._data =<span style="color: #000000"> val; } } registerOnChange(fn: any): <span style="color: #0000ff">void { <span style="color: #008000">//<span style="color: #008000"> 初始化后,执行该方法,并保存控件接收到 change 事件后,调用的函数 <span style="color: #0000ff">this.change =<span style="color: #000000"> fn; } registerOnTouched(fn: any): <span style="color: #0000ff">void<span style="color: #000000"> { } }
import { FormsModule } from '@angular/forms'
import { Component,// 这里的组件名为当前组件的名字
multi: = 2
writeValue(val):
writeValue(val): .childData =
registerOnChange(fn: any): {
.change =
change = (value: any) => {};
然后就可以通过change方法通知外部组件了 set childData(value: number) {
._data =.change(._data);
}
import { Component,multi: = 1.childData ++.change(= (value: any) => {};
writeValue(val): {
.childData = {
.change =
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |