myanmar
myanmar

Reputation: 91

maxlength does not work when ngModel is changed

<input type="text" [(ngModel)]="name" maxlength="10"/>

@Component({...})
export class MyComponent {
 name = "testtesttesttesttest"; // length = 20
}

It displays all the 20 chars in the input field. How to prevent this behaviour? Or maybe how to restrict the 'name' variable to length of 10? I don't want to have a form (FormValidation).

https://stackblitz.com/edit/angular-qnxkad?file=src%2Fapp%2Fapp.component.html

Upvotes: 0

Views: 2037

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

Use [attr.maxlength]

<input type="text"  [attr.maxlength]="10" [(ngModel)]="name" />

EDIT

Since you want to limit it while displaying you should create your own directive with slice as follows,

@Directive({
  selector: '[appLimitTo]',
})
export class LimitToDirective {
    @Input() limit: number;
    constructor(private ngControl: NgControl) {}
    ngOnInit() {
      const ctrl = this.ngControl.control;
      ctrl.valueChanges
        .pipe(map(v => (v || '').slice(0, this.limit)))
        .subscribe(v => ctrl.setValue(v, { emitEvent: false }));
    }
}

STACKBTLIZ DEMO

Upvotes: 3

Related Questions