【问题标题】:Angular 2 Material Input change placeholder dynamicallyAngular 2 Material Input 动态更改占位符
【发布时间】:2017-11-02 14:45:38
【问题描述】:

我想动态更改输入占位符的文本。 console.log 已经给出了更新的字符串,但界面没有更新,所以保留了旧的占位符。 如何让界面识别更改?

document.getElementById(this.implicKey).setAttribute('placeholder', options[i].implication);

console.log(document.getElementById(this.implicKey).getAttribute('placeholder'));

【问题讨论】:

  • 你为什么使用 document.getElementById 你可以使用绑定来改变

标签: javascript angular typescript angular-material placeholder


【解决方案1】:

您可以像这样动态更改输入占位符

<md-input-container class="demo-full-width">
                <input mdInput [(ngModel)]="firstname" placeholder="{{somePlaceholder}}" name="firstname" required>
                <md-error>This field is required</md-error>
            </md-input-container>

组件.ts

somePlaceholder : string = "new value";

现在您可以在类中的任何位置更改 somePlaceholder 值。

【讨论】:

  • 我添加了这个函数 setPlaceholder(value: string) { this.somePlaceholder = value;并将它作为闭包传递给我的服务,以便我可以在数据到达时设置占位符。但它说这是未定义的。我究竟做错了什么?服务的订阅发生在服务类本身内部,我调用了 onSuccess 闭包方法。
【解决方案2】:

我们可以使用属性绑定来做到这一点。

在 HTML 中,使用方括号:

<input formControlName="events" type="text" [placeholder]="newPlaceHolder">

在你的打字稿文件中,定义属性:

newPlaceHolder: string = "original place holder";

然后,更改属性值:

newPlaceHolder= "my new place holder";

【讨论】:

    【解决方案3】:

    这个对我很有用:

    (我用它在 mat-autocomplete 表单字段上显示动态错误)

    在您的 HTML 上:

     [placeholder]="isPlaceHolderShowError('myFormControlName')"
    

    在你的 TS 上:

        isPlaceHolderShowError(myFormControlName) {
        if (this.form.controls[myFormControlName].invalid && this.form.controls[myFormControlName].touched) {
          return 'this is my error text'
        }
        return 'this is the initial placehloder'
      }
    

    【讨论】:

      【解决方案4】:

      另一个选项可能在 HTML 中,使用方括号 attribute binding:

      <input formControlName="events" type="text" [attr.placeholder]="newPlaceHolder">
      

      在您的打字稿文件中,定义属性:

      newPlaceHolder: string = "text binding" 
      

      【讨论】:

        猜你喜欢
        • 2019-03-23
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        • 2019-02-14
        相关资源
        最近更新 更多