当 ngModel 被更改时,最大长度不起作用


<input type="text" [(ngModel)]="name" maxlength="10"/>
@Component({...})
export class MyComponent {
name = "testtesttesttesttest"; // length = 20
}

它显示输入字段中的所有 20 个字符。 如何防止这种行为?或者如何将"name"变量限制为 10 的长度?我不想有一个表单(表单验证(。

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

使用[attr.maxlength]

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

编辑

由于您想在显示时限制它,因此您应该使用 slice 创建自己的指令,如下所示,

@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 演示

最新更新