How to work with current German at Angular 4?

Asked

Viewed 62 times

0

My goal is to have an implementation that the user starts typing is shown in real time a validation message counting the characters being typed, and I do not know how to do this, I know there is the method actualLength

I created a message component as you can see.

import { FormControl } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-message',
  template: `
    <div *ngIf="temErro()" class="ui-message ui-messages-error">
      {{ text }}
    </div>
  `,
  styles: [`
    .ui-messages-error {
      margin: 0;
      margin-top: 4px;
    }
  `]
})
export class MessageComponent {

  @Input() error: string;
  @Input() control: FormControl;
  @Input() text: string;

  temErro(): boolean {
    return this.control.hasError(this.error) && this.control.dirty;
  }

}

Be able to perform this validation in the content field.

  <div class="ui-g-6 ui-md-12 ui-fluid">
        <label>Conteúdo</label>
        <p-editor [style]="{'height':'320px'}" pInputText type="text" name="conteudo"
        [(ngModel)]="noticia.conteudo"
        ngModel #conteudo="ngModel"
        required maxlength="1000">
        </p-editor>


        <app-message [control]="conteudo" error="required"
        text="Informe o conteúdo"></app-message>
        <app-message [control]="conteudo" error="maxlength"
        text="Maximo de {{ conteudo.errors?.maxlength?.requiredLength }} caracteres"  ></app-message>

      </div>

If you type more than 1000 characters this happens.

inserir a descrição da imagem aqui

1 answer

1

My suggestion is to only use the reactive form you should not mix Forms template with reactive Forms

<label class="center-block">Name:
    <p-editor [style]="{'height':'320px'}" pInputText type="text" name="conteudo"
    [formControl]="conteudo">
    </p-editor>     
</label>

{{1000-num}} Characteres restantes

and in the component

  conteudo = new FormControl('', [Validators.required, Validators.maxLength(1000)]); // se vc tiver outros inputs use formGroups
  num = 0;
  ngOnInit() {
    this.conteudo.valueChanges.subscribe(val => this.num = val.length)
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.