在Angular中,你可以使用@Input()
装饰器来传递NgModel的引用。下面是一个示例代码:
首先,在子组件中,使用@Input()
装饰器定义一个属性来接收NgModel的引用:
import { Component, Input, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent implements OnInit {
@Input() ngModelRef: NgModel;
value: string;
ngOnInit() {
this.value = this.ngModelRef.model;
}
onValueChange() {
this.ngModelRef.update.emit(this.value);
}
}
然后,在父组件中,将NgModel的引用传递给子组件的ngModelRef
属性:
import { Component, ViewChild } from '@angular/core';
import { NgModel } from '@angular/forms';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild(NgModel) myNgModel: NgModel;
myValue: string;
}
在父组件中,我们使用@ViewChild(NgModel)
来获取NgModel
的引用,并将其传递给子组件的ngModelRef
属性。在子组件中,我们可以通过ngOnInit()
来初始化子组件中的value
属性,并在onValueChange()
方法中使用NgModel
的update.emit()
来更新父组件中的值。