角度材质 未显示在自定义组件中

2024-01-21

所以我做了很多研究,但我就是无法弄清楚。

我想使用 Angular 材质表单控件制作一个文本框组件

按照此tutorial https://material.angular.io/guide/creating-a-custom-form-field-control#-code-errorstate-code-,我已经实现如下

文本框.component.html

<mat-form-field>
    <input matInput type="text" [placeholder]="placeholder" [(ngModel)]="value" />
    <mat-error>This field is required</mat-error>
</mat-form-field>

文本框.组件.ts

import { Component, Input, forwardRef, OnDestroy, ElementRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl, NgControl } from '@angular/forms';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { MatFormFieldControl } from '@angular/material';
import { Subject } from 'rxjs';
import { FocusMonitor } from '@angular/cdk/a11y';

@Component({
    selector: 'text-box',
    templateUrl: './text-box.component.html',
    styleUrls: ['./text-box.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => TextBoxComponent),
            multi: true
        },
        {
            provide: MatFormFieldControl,
            useExisting: TextBoxComponent
        }
    ]
})
export class TextBoxComponent implements ControlValueAccessor, MatFormFieldControl<any>, OnDestroy {
    static nextId = 0;

    stateChanges: Subject<void> = new Subject<void>();
    id: string = `text-box-${TextBoxComponent.nextId++}`;
    ngControl: NgControl = null;
    focused: boolean = false;
    empty: boolean;
    shouldLabelFloat: boolean;
    disabled: boolean = false;
    errorState: boolean = false;
    controlType?: string = 'text-box';
    autofilled?: boolean;
    describedBy: string = '';

    @Input()
    get placeholder(): string {
        return this._placeholder;
    }
    set placeholder(value: string) {
        this._placeholder = value;
        this.stateChanges.next();
    }
    private _placeholder: string;

    @Input()
    get required(): boolean {
        return this._required;
    }
    set required(value: boolean) {
        this._required = coerceBooleanProperty(value);
        this.stateChanges.next();
    }
    private _required = false;

    @Input() name: string;

    onChange: any = () => {};
    onTouched: any = () => {};

    isDisabled: boolean = false;

    @Input('value') val: string;
    get value(): any {
        return this.val;
    }
    set value(val: any) {
        this.val = val;
        this.errorState = !val;
        this.onChange(val);
        this.onTouched();
        this.stateChanges.next();
    }

    constructor(private fm: FocusMonitor, private elRef: ElementRef<HTMLElement>) {
        fm.monitor(elRef, true).subscribe(origin => {
            this.focused = !!origin;
            this.stateChanges.next();
        });
    }

    writeValue(value: any): void {
        if (value) {
            this.value = value;
        }
    }
    registerOnChange(fn: any): void {
        this.onChange = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }
    setDisabledState?(isDisabled: boolean): void {
        this.isDisabled = isDisabled;
    }

    setDescribedByIds(ids: string[]): void {
        this.describedBy = ids.join(' ');
    }
    onContainerClick(event: MouseEvent): void {
        if ((event.target as Element).tagName.toLowerCase() != 'input') {
            this.elRef.nativeElement.querySelector('input')!.focus();
        }
    }

    ngOnDestroy(): void {
        this.stateChanges.complete();
        this.fm.stopMonitoring(this.elRef);
    }
}

基本上以这样的形式使用它:

<form [formGroup]="someForm" (ngSubmit)="onSubmit()">
    <acs-text-box formControlName="username" [placeholder]="'Form control'"> </acs-text-box>
    <my-button [type]="'submit'">Submit</my-button>
</form>

所以这是我的问题,我试图在 textbox.component.html 模板内进行渲染,但它不起作用

我尝试了一些方法,例如在 textbox.component.ts 中设置 errorState = true 但没有任何反应。

我试过这个

<mat-form-field>
    <acs-text-box formControlName="username" [placeholder]="'Form control'"> </acs-text-box>
    <mat-error>This field is required</mat-error>
</mat-form-field>

它在设置 errorState = true 时工作正常,但是当我将 mat-error 返回到文本框组件模板内部时,它不起作用。

有没有办法在文本框组件模板内进行渲染?或者它只是不能用有角度的材料来实现,我应该以自己的方式实现它?

提前致谢!!


尝试这样做:

<mat-form-field>
    <input matInput type="text" [placeholder]="placeholder" [(ngModel)]="value" required #inputValue="ngModel" />
    <mat-error *ngIf="(inputValue.touched && inputValue.invalid)">This field is required</mat-error>
</mat-form-field>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

角度材质 未显示在自定义组件中 的相关文章

随机推荐