Angular material insert mat-hint to custom formcontrol

Discussão em 'Angular' iniciado por Robin Dijkhof, Outubro 19, 2024.

  1. I have this custom FormControl which holds come complex logic and uses mat-form-field.

    export class ComplexFormControlComponent implements ControlValueAccessor{

    private formControl = new FormControl();

    writeValue(){}
    // Other methods.
    }


    <mat-form-field>
    <mat-label>Complex value</mat-label>
    <input matInput placeholder="complex value" [formControl]="formControl">
    </mat-form-field>


    I'm using this component in one of my forms.

    <form [form]="form">
    <mat-form-field>
    <mat-label>Simplevalue</mat-label>
    <input matInput placeholder="simple value" formControlName="simple">
    </mat-form-field>
    <complex-form-control-component formControlName="complex"></complex-form-control-component>
    </form>


    Now for example when form.simple.value === '' I want to show a hint in the ComplexFormControlComponent. I could simply pass the message to ComplexFormControlComponent but I'd rather pass a mat-hint directly into it.

    Something like this:

    <complex-form-control-component formControlName="complex">
    <mat-hint *ngIf="form.simple.value === ''">Please enter simple value first</mat-hint>
    </complex-form-control-component>


    How can I do this?

    I tried:

    <complex-form-control-component formControlName="complex">
    <ng-template><mat-hint>Hint1</mat-hint><ng-template>
    <ng-template><mat-hint>Hint2</mat-hint><ng-template>
    </complex-form-control-component>


    And in the complex component

    @ContentChildren(TemplateRef) hints: QueryList<TemplateRef<MatHint>>


    <mat-form-field>
    <mat-label>Complex value</mat-label>
    <input matInput placeholder="complex value" [formControl]="formControl">
    <mat-hint>Test</mat-hint>
    <ng-template *ngFor"let hint of hints" [ngTemplateOutlet]="hint"></ng-template>
    </mat-form-field>


    That just places the hint in the HTML but the mat-form-field does not interact with it:

    [​IMG]

    Continue reading...

Compartilhe esta Página