Angular 2 Material 输入框动态更改占位符

17

我想动态更改输入框的占位符文本。 控制台已经给出了更新后的字符串,但界面没有更新,因此旧的占位符仍然存在。 如何让界面识别更改?

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

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

为什么要使用document.getElementById,你可以使用绑定改变。 - CharanRoot
4个回答

24

你可以像这样动态地更改你的输入占位符

<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; } 并将其作为闭包传递给我的服务,以便在数据到达时设置占位符。但它说“this”未定义。我做错了什么?服务的订阅发生在服务类本身内部,我调用了闭包方法 onSuccess。 - Ε Г И І И О

5
我们可以使用属性绑定来实现这一点。
在HTML中,使用方括号:
<input formControlName="events" type="text" [placeholder]="newPlaceHolder">

在您的 TypeScript 文件中,定义属性:
newPlaceHolder: string = "original place holder";

然后,更改属性值:

newPlaceHolder= "my new place holder";

1

另一种选择可能是在HTML中使用方括号和属性绑定

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

在你的 TypeScript 文件中,定义属性:
newPlaceHolder: string = "text binding" 

0

这个对我来说非常好用:

(我用它来显示 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'
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接