Angular 6无法访问指令ngOnInit内的表单控件

时间:2018-10-15 09:51:13

标签: angular6 angular-directive

我正在尝试创建一个角度为6的指令,当基于模板的表单具有无效且被触摸的元素时,它将向表单容器/ div中添加一个css类。

简单来说,我要实现的功能是:(请注意此处的[ngClass]

<div class="col-sm-12 col-md-6  form-group " [ngClass]="{'has-error': !ArabicName.valid  && ArabicName.touched}">
 <label class="control-label">Arabic Name</label>
 <input type="text" class="form-control" name="ArabicName" placeholder="Arabic name" required ngModel #ArabicName="ngModel" />
</div>

所以我创建了一个称为错误标记的指令,我可以将其用作:

<div class="col-sm-12 col-md-6  form-group " errormarker="ArabicName">
 <label class="control-label">Arabic Name</label>
 <input type="text" class="form-control" name="ArabicName" placeholder="Arabic name" required ngModel #ArabicName="ngModel" />
</div>

相关指令代码为:

@Directive({
    selector: '[errormarker]'
})
export class ErrorMarkerDirective implements OnInit, OnDestroy {
    @Input('errormarker') elementName: string;
    control: AbstractControl;
    //hasView = false;
    controlValue$: Observable<any>;
    controlSubscription: Subscription;

    constructor(
        private _fg: ControlContainer,
        private _el: ElementRef,
        private render: Renderer2
    ) { }

    ngOnInit() {
        console.log('inside marker');
        console.log(this.elementName);
        console.log(this.form);
        console.log(this.form.controls[this.elementName]); // <--<This LINE
        this.control = this.form.controls[this.elementName];

        let formSubmit$ = (<FormGroupDirective>this._fg).ngSubmit; 

        this.controlValue$ = merge(this.control.valueChanges, of(''), formSubmit$);
        this.controlSubscription = this.controlValue$.subscribe(() => {
            console.log('inside value');
            this.setVisible();
        });
    }

    private setVisible() {
        if (this.control.invalid && this.control.touched) { //(this.control.dirty || 

            this.render.addClass(this._el.nativeElement,'has-error');
        } else {
            this.render.removeClass(this._el.nativeElement, 'has-error');
        }
    }

    match(error: string) {
        if (this.control && this.control.errors) {
            if (Object.keys(this.control.errors).indexOf(error) > -1) {
                return true;
            }
        }
        return false;
    }

    get form() { return this._fg.formDirective ? (this._fg.formDirective as FormGroupDirective).form : null; }

    ngOnDestroy() {
        this.controlSubscription.unsubscribe();
    }
}

我希望在调用ngOnInit时,表单应该具有控件,可以将侦听器附加到该控件并添加/删除类。

但是,这不起作用,并且当我调试时,我看到窗体的controls属性为空,并且出现错误this.control is undefined

enter image description here

0 个答案:

没有答案