在我的InstagramContentProductionComponent
中,我想使用以前在InstagramPostTextFormComponent
中使用ControlValueAccessor
创建的表单。
我输入了一些代码,但无法访问我的表单。
这是我在下面的代码中写的instagram-content-production.component.html
:
<form [formGroup]="createPostForm">
<div class="form-group">
<app-post-text formControlName="text" (keyup)="test()"></app-post-text>
</div>
</form>
并在instagram-content-production.component.ts
中输入代码:
public text = {};
createPostForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createPostForm = this.fb.group({
text: fb.control({
content: 'abc'
}),
});
}
这是我的instagram-post-text-form.component.ts
的结构:
import {ControlValueAccessor, FormControl, FormGroup, NG_VALUE_ACCESSOR, Validators} from '@angular/forms';
import {Component, forwardRef, OnInit, Renderer2, ViewChild} from '@angular/core';
export const EPANDED_TEXTAREA_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InstagramPostTextFormComponent),
multi: true,
};
@Component({
selector: 'app-post-text',
templateUrl: './instagram-post-text-form.html',
styleUrls: ['./instagram-post-text-form.scss'],
providers: [EPANDED_TEXTAREA_VALUE_ACCESSOR],
})
export class InstagramPostTextFormComponent implements OnInit, ControlValueAccessor {
form: FormGroup;
@ViewChild('textarea') textarea;
onChange: any = () => {
};
onTouched: () => void = () => {
};
constructor(private renderer: Renderer2) {
}
writeValue(value: any): void {
}
registerOnChange(fn): void {
this.form.valueChanges.subscribe(() => {
this.onChange = fn;
});
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
change($event) {
this.registerOnChange($event.target.textContent);
}
touch($event) {
this.registerOnTouched($event.target.textContent);
}
ngOnInit() {
this.form = new FormGroup({
content: new FormControl(null, Validators.required),
});
}
}
这是她的HTML
代码:
<div [formGroup]="form">
<div #textarea contenteditable="true"
class="text-box"
ngDefaultControl formControlName="content"
placeholder="متن ..."
(input)="change($event);touch($event)"
maxlength="2300">
</div>
</div>
当我键入此textarea
表单时,它不会更新,而我仅获得表单('abc'
)的初始值。
我该如何解决此问题?