How to work with currentLength in Angular 4?

0

My goal is to have an implementation that the user start typing to be shown in real time a validation message the count of the characters being typed, being that I do not know how to do this, I know there is the currentLength

I've 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;
  }

}

Get this validation done 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.

    
asked by anonymous 15.03.2018 / 12:12

1 answer

1

My suggestion and use only the reactive form you should not mix template forms 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

  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)
  }
    
20.03.2018 / 14:30