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()/>
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()/>
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();
}
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;
}
}
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);
}
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"/>