要在输入框中显示FormControl的值,我们需要使用[(ngModel)]指令绑定FormControl的value属性。以下是一个示例代码:
HTML:
Component:
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) export class DemoComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() { this.myForm = this.fb.group({ myControl: ['', Validators.required] }); }
}
在上面的示例中,我们创建了一个名为"myForm"的FormGroup对象,其中包含一个名为"myControl"的FormControl,这个FormControl的值被绑定到一个输入框中。在ngOnInit()函数中,我们初始化了FormControl和FormGroup,并设置了一个Validators.required验证器来验证输入的值是否为空。在HTML的输入框中,我们使用了[(ngModel)]指令将FormControl的value属性与输入框绑定起来,这样当FormControl的值改变时,输入框中的值也会自动更新。