angular - 将 FormBuilder 输入值与另一个输入值绑定(bind)

标签 angular

我有一个带有名称里程碑输入的表单。我希望我的里程碑的输入值为里程碑:+名称,并在用户输入名称时自动更新。

我正在尝试使用 ngModel 绑定(bind)来实现此目的。

<!-- My name input -->
<input mdInput [(ngModel)]="phaseName" formControlName="name" placeholder="Nom" required>

在我的 ts 组件构造函数中:

public phaseForm: FormGroup;
phaseName: string;

this.phaseForm = fb.group({
        'name': ['', Validators.required],
        'milestone': ['Milestone: ' + this.phaseName, Validators.required]
    });

但是由于里程碑的默认值是在构造函数中设置的,因此当我的用户键入名称时它不会更新,我应该添加或执行什么操作才能实现绑定(bind)?

最佳答案

you can set like that. after init form builder in ngOnInit() method. if you can use input box inside formgroup. it's already two way binding so no need bind a value. if you want to get form value.

for eg : const phaseFormValue = this.pahseForm.value;
 console.log(phaseFormValue.name);

ngOnInit(): void {
 this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
}

if you can use input box outside. then try this code.

<input mdInput [(ngModel)]="phaseName" (keypress)="handleKeyboardEvent($event)" placeholder="Name">

//组件

@HostListener('document:keypress', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent): void {
            this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
    };

关于angular - 将 FormBuilder 输入值与另一个输入值绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44386984/

相关文章:

尝试为 RouterOutlet 和 NgIf 配置 _source 的 Angular 和错误

IE11 上的 Angular 4 性能/CPU 使用率

javascript - 我在 Angular 5 应用程序中遇到 CORS 问题,即使我从服务器得到响应

javascript - 检查型号 "dirtiness"

html - Ionic2 View 未更新 + 视频

javascript - 停止 Angular 2 中旋转数的解决方案

html - Flexbox:使内联组件扩展父容器的整个宽度

angular - 如何匹配 Angular2 中内存中 web api 中传递的确切 url 参数?

angular - 使用 VSCode 调试 Typescript Protractor 测试

javascript - Angular app.component.html 未渲染新组件