Updating [placeholder] Reactive Form Control Programmatically

允我心安 提交于 2019-12-10 19:54:25

问题


I have the following formControl as part of my Reactive Form:

<input class="input" formControlName="email" [placeholder]="">

I was wondering if there were a way to set the placeholder programmatically?

Something like: this.formGroup.get('email').placeholder = 'Some value';


回答1:


The placeholder is a property of the HTML element itself, not the formGroup. You can directly bind it like you're doing with a component property ([placeholder]="someValue") and Angular's change detection will update it automatically..

You can also grab the element itself via @ViewChild and update it as a property of the element (i.e. vanilla JS):

<input #myInput />

// ...

@ViewChild('myInput') myInput: ElementRef;

// ...

myInput.nativeElement.placeholder = 'New Thing';

If you have a somewhat normalized behavior for these placeholders, you can even extrapolate this into a Directive that accomplishes this behavior in a cleaner way.




回答2:


yo can create a function in your component like

getPlaceholder(key: string): string

this function will generate the placeholder that you want based on the name that you pass

later in your template you can call this function

<input class="input" formControlName="email" [placeholder]="getPlaceholder('email')">

Other solution can be extend the FormControl class.

export class MyCustomFormControl extends FormControl {
  _placeholder: string 
  constructor(...config) {
    super(config)
  }

  set placeholder(key:string){
    this._placeholder = key
  } 
  get placeholder() {
   return this._placeholder
  }
}

and push your custom formControl to the FormGroup . with this approach you going to be able to call from.controls['email'].placeholder




回答3:


You can use ternary operator in [placeholder]. e.g [placeholder]="1==1?'true': 'false'"



来源:https://stackoverflow.com/questions/49117510/updating-placeholder-reactive-form-control-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!