角引用传入的NgModel

时间:2018-11-04 05:29:47

标签: angular angular-components angular-forms ngmodel

在一个组件的HTML模板中:

<input [(ngModel)]='dataModel' #data="ngModel" />
<app-my-component [model]='data'></app-my-component>

app-my-component中:

export class MyComponentComponent implements OnInit {
    @Input() model: NgModel;
}

在运行时,它给我一个错误ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'model: null'. Current value: 'model: address'

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我不知道你为什么要这么做,只需做:

<input [(ngModel)]='dataModel'/>
<app-my-component [model]='dataModel'></app-my-component>

ts:

export class MyComponentComponent implements OnInit {
    @Input() model: string;
}

答案 1 :(得分:0)

尝试使用 ChangeDetectorRef 来告诉Angle NgModel的数据有新变化。

constructor(private cdr: ChangeDetectorRef) {}

ngAfterViewInit() {
    this.cdr.detectChanges();
}