Angular 2 set input max length dynamically

让人想犯罪 __ 提交于 2019-12-07 22:08:48

问题


I would like to get the max length of an input from a service (do an http call to get the value).

Is there any way to do it with calling the service only once?

<input type="text" [attr.maxLength]="getMaxLength()/>

thanks


回答1:


Setting maxLength attribute value to a class property which value is set in contructor or ngOnInit will make it stop calling the service anymore

HTML:

<input type="text" [maxLength]="maxLength"/>

Typescript

  maxLength: number;
  .....
  constructor(private myService: MyService){
    this.maxLength =  this.myService.getMaxLength();
  }

DEMO




回答2:


In your component.ts

maxLenght:number = 0;

ngOnInit() {
  this.service.getMaxLength()
    .subscribe(max => {
      this.maxLenght = max;
     });
}

then in the view

<input type="text" [attr.maxLength]="maxLength"/>




回答3:


Use the method call during the constructor and update a component variable

constructor(private _http: Http) {
    this.getMaxLength().subscribe(data=>{
      console.log(data)
      this.maxLength= data;
      })

  }
  getMaxLength(): Observable<number> {
        return this._http.get(this._url)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

LIVE DEMO




回答4:


You can get the value of max from service and store it in a local value and that can be directly bound to the element.

Please find the example in the link

https://plnkr.co/edit/FX2DH96Femf02XwBUeCO

    @Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      Quantity (between 10 and 100):
      <input type="number" name="quantity" min="{{min}}" max="{{max}}">
      <br/>
      Name (max length - 10 character)
      <input type="text" name="name" [attr.maxLength]="maxTextLen">
    </div>
  `,
})
export class App {
  name:string;
  min : number;
  max : number;
  maxTextLen;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
    this.min = 10;
    this.max = 100;
    this.maxTextLen = 10;

  }
}


来源:https://stackoverflow.com/questions/46829107/angular-2-set-input-max-length-dynamically

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