在Angular中,可以通过使用@ViewChild
装饰器来获取NgModel或FormControlName指令的值。下面是一个示例代码:
HTML模板:
组件类:
import { Component, ViewChild } from '@angular/core';
import { NgModel } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
myValue: string;
@ViewChild('myInput', { static: false })
ngModelDirective: NgModel;
getValue() {
console.log(this.ngModelDirective.value);
}
}
在这个示例中,@ViewChild
装饰器用于获取ngModel
指令,并将其赋值给名为ngModelDirective
的变量。然后,可以在getValue
方法中访问ngModelDirective.value
来获取指令的值。
注意:这个示例假设ExampleComponent
已经导入了NgModel
,并且FormsModule
已经在AppModule
中正确地导入。