BLOG

Angular で maxlength が勝手に 0 になる

# Angular# TypeScript
Angular で maxlength が勝手に 0 になる

要約

  • 動的制御している inputmaxlength が空(null, undefined のとき)勝手に 0 になっていた
  • 原因は [maxLength] でのバインド
  • 解決策は [attr.maxlength] を使う

サンプル

// app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  styleUrls: ["./app.component.scss"],
  templateUrl: "./app.component.html"
})
export class AppComponent {
  public maxLength?: number;
}

 <!-- app.component.html -->
OK: <input type="text" [attr.maxlength]="maxLength"><br><br>
NG: <input type="text" [maxLength]="maxLength">

NGの方は maxLength="0" でレンダリングされているため入力できない。 下記サンプルはv7だが、v11でも同様の現象を確認済み

stackblitz


maxminの他の属性は大丈夫だったので地味な罠だった...🥺

SHARE

新着記事