angular2在父组件怎么使用双向绑定来接收子组件输出的数据,而不是通过方法呢?
本文介绍了angular2在父组件怎么使用双向绑定来接收子组件输出的数据,而不是通过方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
@Input() count: number = 5;
@Output() countChange = new EventEmitter();
change{
this.count ++;
this.countChange.emit(this.count);
}
<app-child-component [(conut)]="conut"></app-child-component>
[(conut)]="conut" 这个会报错
Can't bind to 'conut' since it isn't a known property of 'app-child-component'. 1. If 'app-child-component' is an Angular component and it has 'conut' input, then verify that it is part of this module. 2. If 'app-child-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. 3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
解决方案
ngx-two-way.component.html
<div class="toggle-button-container"> <a href="javascript:;" (click)="toggle()" class="text-close">+</a>
ngx-two-way.component.ts
import {Component, forwardRef,OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-ngx-two-way',
templateUrl: './ngx-two-way.component.html',
styleUrls: ['./ngx-two-way.component.css'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgxTwoWayComponent),
multi: true
}]
})
export class NgxTwoWayComponent implements OnInit,ControlValueAccessor {
constructor() { }
ngOnInit() {
}
private model: any;
public onModelChange: Function = () => {};
public onModelTouched: Function = () => {};
writeValue(value: any) { this.model = value; }
registerOnChange(fn: Function): void { this.onModelChange = fn; }
registerOnTouched(fn: Function): void { this.onModelTouched = fn; } // setDisabledState(val: boolean): void {}
toggle(event) { this.model = this.model; this.onModelChange(this.model); }
}
app.component.html
<p>双向子组件</p>
<app-ngx-two-way [(ngModel)]="pvalue"></app-ngx-two-way>
这篇关于angular2在父组件怎么使用双向绑定来接收子组件输出的数据,而不是通过方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文