Angular2 maxLength for textarea as variable

送分小仙女□ 提交于 2019-12-09 18:13:37

问题


To set max letters number for textarea, we do achieve that by writing: <textarea maxLength="50"></textarea>

but, could I do something like below? Is there some way?

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-create-offer-page',
  template: `
    <textarea maxLength="textareaLength"></textarea>
  `
})
export class CreateOfferPageComponent {
  textareaLength: number = 50;
}

I'm asking because that does not work.


回答1:


You would need [] for Angular to interpret it as binding

 [maxLength]="textareaLength"

This should work for native validation. Angular2 validators don't currently support dynamic values.




回答2:


Sure and it's pretty easy - just use attribute binding like so:

<textarea [attr.maxLength]="textareaLength"></textarea>



回答3:


Expanding a little bit on the answer provided by @rinukkusu, you could even make the attribute optional by adding a ternary operator, like so:

<textarea [attr.maxLength]="textareaLength > 0 ? textareaLength : null"></textarea>

The null value removes the attribute completely from the element, which was something I needed.



来源:https://stackoverflow.com/questions/38249022/angular2-maxlength-for-textarea-as-variable

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