【发布时间】:2018-01-25 18:07:19
【问题描述】:
我的自定义文本输入:
import { Component, Inject, Injector, Input, Optional, ViewChild, Output,
EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, NgModel } from '@angular/forms';
import { ValueAccessorBase } from '../base-elements/value-accessor';
@Component({
selector: 'sm-input',
templateUrl: './sm-input.component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: SmInputComponent,
multi: true,
}],
styleUrls: ['./sm-input.component.scss'],
})
export class SmInputComponent extends ValueAccessorBase<string> {
constructor(injector: Injector) {
super(injector);
}
}
sm 输入 html: (我删除了不必要的)
<div>
<div *ngIf="label">
<label>
{{label}}
</label>
</div>
<div>
<input
type="text"
pInputText
[(ngModel)]="value"
/>
</div>
</div>
我的表格:
import { HttpModule, Http } from '@angular/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'sm-input-example-in-reactive-from',
templateUrl: './sm-input-example-in-reactive-from.component.html',
styleUrls: ['./sm-input-example-in-reactive-from.component.scss']
})
export class SmInputExampleInReactiveFromComponent {
public firstName: string = "Bob";
myReactiveForm: FormGroup;
constructor(fb: FormBuilder, private http: Http) {
this.myReactiveForm = fb.group ({
myField: [this.firstName, [Validators.required]],
});
}
onSubmit(value) {
console.log(`Submit: ${JSON.stringify(value)}`);
}
}
html 表单
<p-panel header="Reactive Form">
<form action="" [formGroup]="myReactiveForm" (ngSubmit)="onSubmit(myReactiveForm.value)">
<div class="ui-grid-row">
<sm-input
label="First Name"
formControlName="myField">
</sm-input>
</div>
<div class="ui-grid-row">
<div class="ui-g-2 ui-g-offset-5">
<button type="Submit" class="" pButton [disabled]="!myReactiveForm.valid">Submit</button>
</div>
</div>
</form>
</p-
在我在 [(ngModel)]="value" 中使用的 sm-input html 中。
它正在工作。 但我不想在 [(ngMode)]="值"
因为响应式表单不需要使用 ngMode。 我读了这篇文章 Two way binding in reactive forms
在驱动形式和反应形式之间混合并不是一个好主意。
角度文档:https://angular.io/guide/reactive-forms
"...因此,ngModel 指令不属于 ReactiveFormsModule"。
我该怎么办?
谢谢。
【问题讨论】:
-
你有什么问题?如果您不想使用 ngModel,请不要使用它。
-
您似乎了解数据绑定,您在示例中使用了它,因此只需在输入值或您需要的任何地方再次使用它...
-
“所以只需在输入值或任何你需要的地方再次使用它”。我需要将 formControler (firstName) 绑定到我的自定义组件。在主机组件(表单)中,我创建了自定义组件(sm-input)的实例,其中 formControlName 绑定到 form.ts 中的 firstName。如何在没有 [(ngModel)] 的情况下将 formControler (firstName) 绑定到我的自定义输入组件。
标签: angular textinput angular-reactive-forms two-way-binding