3xG*_*Guy 5 typescript angular angular-reactive-forms angular-forms
我已经构建了一个名为 的控件TextBox,为了简单起见,我将只在此发布该控件的相关部分。
@Component({
selector: 'app-textbox',
template:
`
<input [(ngModel)]="value" [disabled]="disabled" />
`,
styleUrls: ['./textbox.component.css']
})
export class TextboxComponent implements OnInit, ControlValueAccessor {
constructor() { }
writeValue(obj: any): void {
this._value = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
disabled = false;
onChange:()=>{}
onTouch:()=>{};
private _value:string;
public get value():string {
return this._value
}
public set value(value:string){
this._value = value;
}
ngOnInit(): void {
}
Run Code Online (Sandbox Code Playgroud)
我的 app.component.ts 看起来像:
@Component({
selector: 'app-root',
template:
`
<form [formGroup]="form" novalidate>
<div>
<label >Name</label>
<app-textbox formControlName="name"></app-textbox>
</div>
</form>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
/**
*
*/
constructor(private formBuilder:FormBuilder) {
}
form = this.formBuilder.group({
name:['', Validators.required]
})
model:NameModel = {
name:'test'
}
ngOnInit(): void {
this.form.get('name').setValue(this.model.name);
}
}
interface NameModel{
name:string;
}
Run Code Online (Sandbox Code Playgroud)
当我运行该应用程序时,我希望文本框将填充值测试。
有人可以解释一下为什么不是吗?
this.form.get('name')?.value当我得到正确的值时我会添加。
您只需将值设置this.form.get('name').setValue(this.model.name);为ngAfterViewInit而不是ngOnInit,或者您必须在其之后调用:
this.form.updateValueAndValidity();
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这里有两个注意事项您应该注意:
TextboxComponent,因此您必须onChange在值设置器中调用已注册的方法,如下所示:private _value: string;
public get value(): string {
return this._value;
}
public set value(value: string) {
this._value = value;
this.onChange(value);
}
Run Code Online (Sandbox Code Playgroud)
FormGroup中初始化ngOnInit,并直接设置默认值name,如下所示:form: FormGroup;
ngOnInit(): void {
this.form = this.formBuilder.group({
name: [this.model.name, Validators.required],
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3579 次 |
| 最近记录: |