Angular 2 Material 动态输入更改占位符
Angular 2 Material Input change placeholder dynamically
我想动态更改输入占位符的文本。
console.log 已经给出了更新后的字符串,但是界面没有更新,所以旧的占位符仍然存在。
如何让界面识别更改?
document.getElementById(this.implicKey).setAttribute('placeholder', options[i].implication);
console.log(document.getElementById(this.implicKey).getAttribute('placeholder'));
您可以像这样动态更改您的输入占位符
<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>
component.ts
somePlaceholder : string = "new value";
现在您可以在 class 中的任何位置更改 somePlaceholder 值。
我们可以使用 属性 绑定来做到这一点。
在HTML中使用方括号:
<input formControlName="events" type="text" [placeholder]="newPlaceHolder">
在您的打字稿文件中,定义 属性:
newPlaceHolder: string = "original place holder";
然后,更改 属性 值:
newPlaceHolder= "my new place holder";
这个非常适合我:
(我用它来显示 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'
}
另一个选项可能在 HTML 中,使用方括号 attribute binding:
<input formControlName="events" type="text" [attr.placeholder]="newPlaceHolder">
在您的打字稿文件中,定义 属性:
newPlaceHolder: string = "text binding"
我想动态更改输入占位符的文本。 console.log 已经给出了更新后的字符串,但是界面没有更新,所以旧的占位符仍然存在。 如何让界面识别更改?
document.getElementById(this.implicKey).setAttribute('placeholder', options[i].implication);
console.log(document.getElementById(this.implicKey).getAttribute('placeholder'));
您可以像这样动态更改您的输入占位符
<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>
component.ts
somePlaceholder : string = "new value";
现在您可以在 class 中的任何位置更改 somePlaceholder 值。
我们可以使用 属性 绑定来做到这一点。
在HTML中使用方括号:
<input formControlName="events" type="text" [placeholder]="newPlaceHolder">
在您的打字稿文件中,定义 属性:
newPlaceHolder: string = "original place holder";
然后,更改 属性 值:
newPlaceHolder= "my new place holder";
这个非常适合我:
(我用它来显示 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'
}
另一个选项可能在 HTML 中,使用方括号 attribute binding:
<input formControlName="events" type="text" [attr.placeholder]="newPlaceHolder">
在您的打字稿文件中,定义 属性:
newPlaceHolder: string = "text binding"