In my coding project, I have developed a custom control named TextBox
. In this post, I will only showcase the relevant snippets of code related to this control.
@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 {
}
Additionally, the structure of my app.component.ts file is as follows:
@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;
}
Upon running the application, I anticipated that the textbox would display the text "test." However, this was not the case. Can someone provide insight into why this may be happening?
It's worth noting that when I execute this.form.get('name')?.value
, the correct value is returned.