访问组件文件(打字稿)中的 NgModel 对象(不是值)



我正在使用[(ngModel)]- 双向绑定。

.HTML-

<input
type="text" 
[(ngModel)]="emailInput" 
#toemail="ngModel" 
[email]="true" 
[style.color]="toemail.invalid && toemail.touched ? 'red' : ''"
/>

TS -

public emailInput: string;

在组件文件中,我可以在变量emailInput中获取字符串形式的输入值。

但是我希望ngModel对象位于组件打字稿文件中的某些变量中。虽然我可以使用引用变量toemail在 html 文件中访问它,但希望在组件文件中使用它。

有什么办法可以做到这一点吗?

您可以使用ViewChild来实现这一点。

import { Component, ViewChild } from "@angular/core";
import { NgModel } from "@angular/forms";
@Component({
//...
})
export class SomeComponent {
@ViewChild('toemail', {static: true}) toemail: NgModel;
ngOnInit() {
console.log(this.toemail) // ngModel
}
}

这将使您能够访问ngModel

最新更新