我写了一个compoent来包装一个wysiwyg javascript插件 我已经实现了ControlValueAccesor并将其绑定到我的表单中的ngModel 但该字段的值始终是不明确的 即使包裹wyiwug的组件的内部_value是正确的 这是代码。
更改父级中的content
值会更改子表单控件组件的内容。
trumobowyg.ts
import {Component, OnInit, ElementRef, forwardRef} from '@angular/core';
import {
ControlValueAccessor, NG_VALUE_ACCESSOR, Validator, AbstractControl, ValidationErrors,
NG_VALIDATORS
} from "@angular/forms";
@Component({
selector: 'trumbowyg',
templateUrl: './trumbowyg.component.html',
styleUrls: ['./trumbowyg.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TrumbowygComponent),
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => TrumbowygComponent),
multi: true,
}
]
})
export class TrumbowygComponent implements OnInit, ControlValueAccessor, Validator{
private _content: string;
private _elm: any;
propagateChange = (_: any) => {};
propagateTouch = () => {};
constructor(private elmRef: ElementRef) { }
ngOnInit() {
let self = this;
this._elm = (<any> $('div', this.elmRef.nativeElement)).trumbowyg();
this._elm
.on('tbwfocus', function() {
self.propagateTouch();
})
.on('tbwchange', function() {
self.content = self._elm.trumbowyg('html');
})
}
get content() {
return this._content;
}
set content(v: any) {
if (v !== this._content) {
this._content = v;
this.propagateChange(v);
}
}
writeValue(obj: any): void {
if(obj !== undefined) {
this._content = obj;
this._elm.trumbowyg('html', this._content);
}
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.propagateChange = fn;
}
validate(c: AbstractControl): ValidationErrors|any {
( this._content && this._content.length > 0 ) ? null : {
valid: false,
}
}
}
形式
<form #f="ngForm" (ngSubmit)="onCommentSubmit()">
<ng-container *ngIf="(user | async)" class="">
<trumbowyg [(ngModel)]="content" name="content"></trumbowyg>
<div class="d-flex flex-row-reverse pt-3">
<button type="submit" class="btn btn-primary" [disabled]="!form.valid"> Valider </button>
</div>
</ng-container>
</form>
答案 0 :(得分:-1)
似乎永远不会调用内容设置器(因此propagateChange
也是如此),因为值通过writeValue(obj:any)
方法,您可以将新值直接分配给_content