【发布时间】:2021-11-08 16:09:42
【问题描述】:
我已经构建了一个名为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 {
}
我的 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;
}
当我运行应用程序时,我希望文本框会填充值 test。
有人可以解释为什么不是吗?
我会在this.form.get('name')?.value 得到正确值时添加。
【问题讨论】:
-
尝试将
this.form.get('name').setValue(this.model.name);移动到ngAfterViewInit而不是ngOnInit -
谢谢@AmerYousuf 那是anwser。如果您将其添加到 anwser,我会接受它。
-
谢谢,我在回答中添加了一些注释。
标签: angular typescript angular-reactive-forms angular-forms